I am trying to update a sql db in an "IF THEN" statement but I am getting :
ExecuteNonQuery: Connection property has not been initialized.
When I run my code.
Private m_cn As New SqlConnection
If oldcost <> newcost Then
'Dim myconnect As New SqlClient.SqlConnection
m_cn.ConnectionString = "Data Source=localhost;Initial Catalog=tires;Integrated Security=True"
m_cn.Open()
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
'm_cn.Open()
mycommand.CommandText = "INSERT INTO tire_price_changes (change_date, old_cost, old_retail,new_cost,new_retail,tire_id) VALUES (#change_date, #Nold_cost, #old_retail, #new_cost, #new_retail, #tire_id)"
Try
mycommand.Parameters.Add("#change_date", SqlDbType.Date).Value = tiredate
mycommand.Parameters.Add("#old_cost", SqlDbType.NVarChar).Value = oldcost
mycommand.Parameters.Add("#old_retail", SqlDbType.VarChar).Value = oldretail
mycommand.Parameters.Add("#new_cost", SqlDbType.VarChar).Value = newcost
mycommand.Parameters.Add("#new_retail", SqlDbType.NVarChar).Value = newretail
mycommand.Parameters.Add("#tire_id", SqlDbType.NVarChar).Value = m_introwposition
mycommand.ExecuteNonQuery()
MsgBox("Success")
Catch ex As System.Data.SqlClient.SqlException
MsgBox(ex.Message)
End Try
End If
It won't be initialized this way. Either manually set myCommand.Connection property or create the command using CreateCommand:
myCommand = m_cn.CreateCommand();
You're not connecting the command and the connection.
Try this before executing it:
mycommand.Connection = m_cn;
You can also ask the connection object to create the command object for you, in which case it will set this itself:
Dim mycommand As SqlClient.SqlCommand = Connection.CreateCommand()
Additionally, remember to call Dispose on these objects when you're done with them.
Related
In the Database, I used an assigned ProgName = varchar,MaleCuteOff = int,FemaleCutOff=int, and I'm trying to collect User input for the values, but I'm getting an Error
Conversion from string "INSERT INTO CutOff_Point((ProgN" to type
integer is not valid.
Sub save()
Dim query As String = "INSERT INTO CutOff_Point (ProgName, MaleCutOff, FemaleCutOff) VALUES (#colProg, #colMale, #colFemale)"
Using con As New SqlConnection("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True")
Using com As New SqlCommand()
With com
.Connection = con
.CommandType = query
.Parameters.AddWithValue("#colProg", cmbProg.SelectedItem.ToString)
.Parameters.AddWithValue("#colMale", txtMaleCut.Text.ToString)
.Parameters.AddWithValue("#colFemale", txtFemaleCut.Text.ToString)
End With
Try
con.Open()
com.ExecuteNonQuery()
Catch ex As SqlException
MessageBox.Show(ex.Message.ToString(), "Saving data Not Complete")
End Try
End Using
End Using
End Sub
This:
.CommandType = query
should be setting Commandtext, not CommandType. Why set those properties like that in the first place, when you can use the constructor?
Using com As New SqlCommand(query, con)
I am a beginner and really need help. I want to display data from the database and assign the values to the textboxes and a combobox on a form, but I get this error
Incorrect syntax near "="
It appears is on this line
myreader = cmd.ExecuteReader
Please - any help?
Sub ref()
Dim conn As New SqlConnection
conn.ConnectionString = ("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True")
conn.Open()
Dim strsql As String
strsql = "SELECT ProgName,MaleCuteOff,FemaleCutOff from CutOff_Point where ProgName=" + cmbCourse.SelectedItem + ""
Dim cmd As New SqlCommand(strsql, conn)
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
txtFemale.Text = myreader("FemaleCutOff")
txtMale.Text = myreader("MaleCuteOff")
conn.Close()
End Sub
You should always use SQL parameters to pass parameters to SQL - it avoids embarrasing problems like single quotes breaking the query and deliberate SQL injection attacks.
It's probably best to make sure that there is a selected value before trying to use it.
Some things, e.g. database connections, use "unmanaged resources" and it is necessary to use the Dispose() method to make sure that things are cleaned up afterwards. The Using statement is a convenient way to get the computer to take care of that for you.
I didn't see a need for the query to return the value that was passed to it (ProgName).
You will need to adjust the .SqlDbType and .Size to match the database column.
Option Strict On
' ... other code
Sub Ref()
If cmbCourse.SelectedIndex >= 0 Then
Dim sql As String = "SELECT MaleCuteOff, FemaleCutOff FROM CutOff_Point WHERE ProgName = #ProgName"
Dim connStr = "Data Source=.\;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True"
Using conn As New SqlConnection(connStr),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#ProgName", .SqlDbType = SqlDbType.VarChar, .Size = 99, .Value = cmbCourse.SelectedItem})
conn.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
If rdr.HasRows Then
rdr.Read()
txtFemale.Text = rdr.GetInt32(0).ToString()
txtMale.Text = rdr.GetInt32(1).ToString()
End If
End Using
End If
End Sub
P.S. Shouldn't UEW_ADMISSION_CHEAKER be UEW_ADMISSION_CHECKER? It's best to have things spelt correctly as it is easier to type them.
First of all this Block of Code is not OK. You could use :
Using....End Using Method.
SqlCommand.Parameters Property for security issues.
Connection Strings and Configuration Files for security issues.
Allow me to rewrite your Code using the above methods.
Private Sub RetrieveAndDisplayCutOff()
Dim sbMale As New StringBuilder
Dim sbFemale As New StringBuilder
Dim strsql As String =
"SELECT MaleCutOff,FemaleCutOff FROM CutOff_Point WHERE ProgName = #ComboItem"
Using conn As New SqlConnection("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True"),
CMD As New SqlCommand(strsql, conn)
CMD.Parameters.Add("#ComboItem", SqlDbType.VarChar).Value = ComboBox1.SelectedItem.ToString
conn.Open()
Using MyReader As SqlDataReader = CMD.ExecuteReader
While MyReader.Read 'Returns False if no more rows
'OP mentioned in comments that these fields were int
sbMale.AppendLine(MyReader.GetInt32(0).ToString)
sbFemale.AppendLine(MyReader.GetInt32(1).ToString)
End While
End Using
End Using
txtMale.Text = sbMale.ToString
txtFemale.Text = sbFemale.ToString
End Sub
Protected Sub login_btn_Click(sender As Object, e As EventArgs) Handles login_btn.Click
Dim connString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
connString = "Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
sql = "select NET_ID, Password from User"
connection = New SqlConnection(connString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
If (Password.Text = sqlReader("Password") And NET_ID.Text = sqlReader("NET_ID")) Then
Response.Redirect("Creation.aspx")
End If
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
I always get the msg box saying that connection can noy be established.
I tried to open SQL Server Management Studio at the same time the code running but I didn't anything.
From your exception text:
Incorrect syntax near the keyword 'User'
User is reserved keyword in SQL Server.
Basically not recommended to create table having name equals to reserved keywords, but if you really need this name, you have to surround it with square brackets in your query like this:
select NET_ID, Password from [User]
I from what I can see your connection string looks like it's creating the error you forget to escape the "\" character.
additional you can move code inside try block so that you get specific error code
so to escape you can change the line to become
connString = #"Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True";
OR
connString = "Data Source=.\\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True";
so update your code to become:
Protected Sub login_btn_Click(sender As Object, e As EventArgs) Handles login_btn.Click
Dim connString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
Try
connString = #"Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
//OR USE BELOW
//connString = "Data Source=.\\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
sql = "select NET_ID, Password from User"
connection = New SqlConnection(connString)
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
If (Password.Text = sqlReader("Password") And NET_ID.Text = sqlReader("NET_ID")) Then
Response.Redirect("Creation.aspx")
End If
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
Protected Sub login_btn_Click(sender As Object, e As EventArgs) Handles login_btn.Click
Dim connString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim sql As String
connString = "Data Source=.\SQLExpress;Initial Catalog=Suivi_Invst;Integrated Security=True"
//Instead of
sql = "select NET_ID, Password from User"
//I used this
sql = "SELECT [NET_ID], [Password] FROM [User] "
And it worked
connection = New SqlConnection(connString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
Dim sqlReader As SqlDataReader = command.ExecuteReader()
While sqlReader.Read()
If (Password.Text = sqlReader("Password") And NET_ID.Text = sqlReader("NET_ID")) Then
Response.Redirect("~/Request/Creation.aspx")
End If
End While
sqlReader.Close()
command.Dispose()
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
thanks everyone
Every time I tried to connect to the database it give me this error "The ConnectionString property has not been initialized"
what can I do to solve this?
here are my codes
Module Module1
Function GetInfoForStudent(ByRef QueryName As String, ByVal UserName As String, ByVal Password As String) As DataTable
Using Con As New SqlConnection
Try
Using OleCon As New SqlConnection
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library
Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Con.Open()
Dim Cmd As SqlCommand = Con.CreateCommand()
Cmd.CommandType = CommandType.StoredProcedure
Cmd.CommandText = QueryName
Cmd.Parameters.AddWithValue("#user", UserName)
Cmd.Parameters.AddWithValue("#pass", Password)
Dim da As New SqlDataAdapter(Cmd)
Dim ds As New DataTable()
da.Fill(ds)
Return ds
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Using
End Function
End Module
Sub ShowStudentInfo()
Dim dt As DataTable = GetInfoForStudent("MyStoredProcName", "#user", "#pass")
' Since (presumably) only one is returned
With dt.Rows(0)
' Assign your text boxes
StudentIDTextBox.Text = .Item("StudentID")
LoginIDTextBox.Text = .Item("LoginID")
Student_NameTextBox.Text = .Item("Student Name")
Student_addressTextBox.Text = .Item("Student address")
End With
End Sub
You never assigned your connection string to the connection object, just like the error is saying.
Insert a line setting the connection string before con.open.
Con.connectionstring = connection
Con.Open()
Or better yet, change your using statement as follows
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Using Con As New SqlConnection(connection)
You are creating the connection string object but never assigning it to your SqlCommand object.
After running the following sub (VS debugger), I try to detach the database in SSMS, but it shows the connection open still and won't let me detach. If I close program in debugger, the database shows no connections. I check the dataadapter's connection in the finally block and is shows closed. What gives
Private Function ClientMasterDBFiles(ByVal MasterClientDBConnection As String, ByVal DBName As String) As DataTable
Dim da As SqlDataAdapter
Dim ds As DataSet
Try
ds = New DataSet
da = New SqlDataAdapter
da.SelectCommand = New SqlCommand
With da.SelectCommand
.CommandType = CommandType.StoredProcedure
.Connection = New SqlConnection(MasterClientDBConnection)
.CommandText = "QT_DataSync_GetDBFileLocations"
.Parameters.Add(New SqlParameter("#DBName", SqlDbType.VarChar, 100))
.Parameters.Item("#DBName").Direction = ParameterDirection.Input
.Parameters.Item("#DBName").Value = DBName
.CommandType = CommandType.StoredProcedure
.CommandTimeout = 10
End With
da.Fill(ds)
If ds.Tables.Count > 0 Then
Return ds.Tables(0)
End If
Catch ex As Exception
m_ErrorLog.HandleException(ex)
Throw
Finally
If Not da Is Nothing Then da.Dispose()
If Not ds Is Nothing Then ds.Dispose()
da = Nothing
ds = Nothing
End Try
End Function
EDIT
I was wrong all along.
Your problem is that the .Net SqlClient classes pool connections.
You need to explicitly close the SqlCommand's Connection, like this:
If Not da Is Nothing Then da.SelectCommand.Connection.Close()
However, you should use a Using statement instead, like this:
Dim ds As DataSet
Try
Using da As SqlDataAdapter, _
da.SelectCommand = New SqlCommand, _
da.Connection = New SqlConnection(MasterClientDBConnection)
With da.SelectCommand
.CommandType = CommandType.StoredProcedure
.CommandText = "QT_DataSync_GetDBFileLocations"
.Parameters.Add(New SqlParameter("#DBName", SqlDbType.VarChar, 100))
.Parameters.Item("#DBName").Direction = ParameterDirection.Input
.Parameters.Item("#DBName").Value = DBName
.CommandType = CommandType.StoredProcedure
.CommandTimeout = 10
End With
da.Fill(ds)
If ds.Tables.Count > 0 Then
Return ds.Tables(0)
End If
End Using
Catch ex As Exception
m_ErrorLog.HandleException(ex)
Throw
End Try
Also, you shouldn't dispose the DataSet, since you're returning one of its tables.