As you can probably very soon see, I am a complete newbie at VB.NET, and I am having some trouble getting output from a stored procedure in SQL Server 2005.
This is the code I use
Dim con As New SqlConnection
Dim cmd As New SqlCommand("esp_getDates", con)
Dim par As New SqlParameter("#PlaceID", SqlDbType.Int, 3906)
con.ConnectionString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=ProgramDB;User ID=test;Password=test"
con.Open()
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters("#PlaceID").Direction = ParameterDirection.Output
cmd.ExecuteNonQuery()
con.Close()
I get the error;
An SqlParameter with ParameterName
'#PlaceID' is not contained by this
SqlParameterCollection.
Does anyone see what I'm doing wrong / have any suggestions how I can fix it? Code examples would be very helpful and any help is much appreciated.
You aren't actually adding the parameter to the cmd.Parameters collection:
cmd.Parameters.Add(par)
Alternatively, just add the parameter without instantiating the Parameter object explicitly:
cmd.Parameters.Add("#PlaceID", SqlDbType.Int)
cmd.Parameters("#PlaceID").Value = 3906
Also, I'd follow the principle of using a variable as close to the declaration as possible and reorganize things this way:
Dim con As New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=ProgramDB;User ID=test;Password=test")
con.Open()
Dim cmd As New SqlCommand("esp_getDates", con)
Try
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#PlaceID", SqlDbType.Int)
cmd.Parameters("#PlaceID").Value = 3906
cmd.ExecuteNonQuery()
Finally
If cmd IsNot Nothing Then cmd.Dispose()
If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then cn.Close()
End Try
Related
I am new to the vb and I want to create project where if I click this button, form 2 will show and the information from it will change depends on what room button I click. i know how to connect a database but I am so clueless on how to make it that way, please help me. Thank you everyone
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\arima\Documents\Consumer & rooms Database.mdb")
Yup, Stuck
You also need an OleDbCommand associated with the connection. The OleDbCommand.CommandText property is where your SQL statements go. Then you can .Open() the connection, so the command object can execute the SQL statements.
Here's the general idea:
Using con As New OleDbConnection("connection string here"), _
cmd As New OleDbCommand("SELECT * FROM MyTable WHERE MyColumn = ?", con)
cmd.Parameters.Add("?", OleDbType.VarWChar, 25).Value = "SomeValue"
con.Open()
Using rdr As OleDbDataReader = cmd.ExecuteReader()
While rdr.Read()
' Do something with each record
End While
End Using
End Using
Alternatively, you can use an OleDbDataAdapter to fill a DataTable or DataSet:
Dim dt As New DataTable
Using con As New OleDbConnection("connection string here"), _
da As New OleDbDataAdapter("SELECT * FROM MyTable WHERE MyColumn = ?", con)
da.SelectCommand.Parameters.Add("?", OleDbType.VarWChar, 25).Value = "SomeValue"
da.Fill(dt)
End Using
My question is my code has problem or not to insert into database. Why I cannot insert it?
I think the data has saved but it not show in database. Please help me see it, thank you.
Dim con As New SqlClient.SqlConnection
Dim cmd As New SqlClient.SqlCommand
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\HTPdatabase.mdf;Integrated Security=True"
cmd.CommandText = "INSERT INTO Customer (Username,Password,Name,IC,Address,Email,Carpark,topup)VALUES(#Username,#password,#Name,#IC,#address,#Email,#Carpark,#topup)"
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#Username", UsernameTextBox.Text)
cmd.Parameters.AddWithValue("#password", PasswordTextBox.Text)
cmd.Parameters.AddWithValue("#Name", DBNull.Value)
cmd.Parameters.AddWithValue("#IC", DBNull.Value)
cmd.Parameters.AddWithValue("#address", DBNull.Value)
cmd.Parameters.AddWithValue("#Email", DBNull.Value)
cmd.Parameters.AddWithValue("#Carpark", DBNull.Value)
cmd.Parameters.AddWithValue("#topup", DBNull.Value)
MsgBox("Successfully register!Please remind customer to update own profile,Thank you !")
cmd.ExecuteNonQuery()
con.Close()
End Sub
As per your code it looks ok but
Place
MsgBox("Successfully register!Please remind customer to update own profile,Thank you !")
below
cmd.ExecuteNonQuery()
because during cmd.ExecuteNonQuery() code may fail and exception may raise.
I am trying to figure out why I am getting an error of 'Object reference not set to an instance of an object.' when my winforms code runs. I have set a breakpoint on the sql statement and stepped into the code and it shows as the line: Using dr = oledbCmd.ExecuteReader()
I am still learning vb.Net so would appreciate some help as to how to overcome this error. Many thanks
DBConnection.connect()
sql = "SELECT * from Boxes WHERE Customer = ? AND Status = 'I'"
Dim cmd As New OleDb.OleDbCommand
cmd.Parameters.AddWithValue("#p1", cmbCustomer.Text)
cmd.CommandText = sql
cmd.Connection = oledbCnn
dr = cmd.ExecuteReader
Using dr = oledbCmd.ExecuteReader()
While dr.Read()
Dim LV As New ListViewItem
With LV
.UseItemStyleForSubItems = False
.Text = dr(1).ToString()
.SubItems.Add(dr(2).ToString())
End With
lvSelectRequestItems.Items.Add(LV)
End While
End Using
cmd.Dispose()
dr.Close()
oledbCnn.Close()
DBConnect module
Imports System.Data.OleDb
Module DBConnection
Public connetionString As String = My.Settings.storageConnectionString
Public oledbCnn As New OleDbConnection
Public oledbCmd As OleDbCommand
Public dr As OleDbDataReader
Public sql As String
Sub connect()
'connetionString = My.Settings.storageConnectionString
oledbCnn.ConnectionString = connetionString
oledbCnn.Open()
End Sub
End Module
I saw several mistakes. Look to the comments for reasons for the changes
Dim sql As String = "SELECT * from Boxes WHERE Customer = ? AND Status = 'I'"
'.Net uses connection pooling, such that you're better using a new connection object for each query
'Also, a Using block will ensure the connection is closed, **even if an exception is thrown**
' The original code would leak connections when exceptions occured, eventually locking you out of the db
Using cn As New OleDb.OleDbConnection("Connection string here"), _
cmd As New OleDb.OleDbCommand(sql, cn) 'set CommandText BEFORE adding parameters
'Use explicit parameter types
cmd.Parameters.Add("?", SqlDbType.NVarChar, 50).Value = cmbCustomer.Text
cn.Open()
Using dr As OleDb.OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
Dim LV As New ListViewItem
With LV
.UseItemStyleForSubItems = False
.Text = dr(1).ToString()
.SubItems.Add(dr(2).ToString())
End With
lvSelectRequestItems.Items.Add(LV)
End While
dr.Close()
End Using
End Using
You have failed to properly bind the SqlConnection to the SqlCommand object.
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim command As New SqlCommand(queryString, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
End While
End Using
See: MSDN
Edit: Requested adjustment to aid in clarity:
Using connection As New Data.SqlClient.SqlConnection
Dim sql As String = "SELECT * from Boxes WHERE Customer = ? AND Status = 'I'"
connection.Open()
Using command As New Data.SqlClient.SqlCommand(Sql, connection)
command.Parameters.AddWithValue("#p1", cmbCustomer.Text)
dr = command.ExecuteReader()
While dr.Read()
Dim LV As New ListViewItem
With LV
.UseItemStyleForSubItems = False
MediaTypeNames.Text = dr(1).ToString()
.SubItems.Add(dr(2).ToString())
End With
lvSelectRequestItems.Items.Add(LV)
End While
End Using
End Using
Your code should look something like that.
you have a fair amount of potential issues going on here.
1-you are using your dr variable twice. once before the using, which is probably causing your error. then again in for using, which does not look right because it is not the cmd variable used to execute the reader. so change this part of your code:
cmd.CommandText = sql
cmd.Connection = oledbCnn
dr = cmd.ExecuteReader
Using dr = oledbCmd.ExecuteReader()
to this:
cmd.CommandText = sql
cmd.Connection = oledbCnn
Using dr = cmd.ExecuteReader()
2-you are not showing if oledbCnn has been opened yet. I'm assuming your DBConnection.connect() function is doing this and olebCnn is a variable that function sets and opens
3-I'm not sure if the question mark in your query string will work. Even if it does you should replace it with the parameter name. so your query string should be:
sql = "SELECT * from Boxes WHERE Customer = #p1 AND Status = 'I'"
lastly you should probably show all the code for the sub(or function) this is for so we can get a full picture. example dr must be declared before the using else you would get a build error.
I have this code that populates a datagridview with data from ms access:
Dim con As New OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim Sql As String
Sql = "SELECT * FROM myTable WHERE case_no=?"
Try
con.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=Sample.accdb;Persist Security Info=True;Jet OLEDB:Database Password=dbadmin2010"
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand(Sql, con)
da.SelectCommand = cmd
cmd.Parameters.AddWithValue("case_no", case_no)
Dim ds As DataSet = New DataSet
da.Fill(ds, "Case Info")
DataGridView1.DataSource = ds.Tables("Case Info")
Catch ex As Exception
MsgBox(ex.Message)
End Try
Now I had just finished creating a query from design view within MS Access itself, is there a way to call that query and retrieve the results to my datagridview?
Just use the query name and set the command type, for example, in addition to what you already have, you can use the following notes:
Try
con.ConnectionString = enter_connection_string_here
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "NameOfQuery"
da.SelectCommand = cmd
cmd.Parameters.AddWithValue("case_no", case_no)
da.Fill(ds, "Case Info")
Take the following example...
Using cn As New SqlConnection(ConnectionString)
Try
Dim cmd As SqlCommand = New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
From my research today is sounds as though this is basically okay but the SqlCommand is not being disposed of.
Question -> Which of the following examples is the best way to deal with this?
Example 2 - Dispose manually
Using cn As New SqlConnection(ConnectionString)
Try
Dim cmd As SqlCommand = New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
cmd.Dispose()
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
Example 3 - Automatic disposing with the Using statement
Using cn As New SqlConnection(ConnectionString)
Try
Using cmd As New SqlCommand
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
End Using
Catch ex As Exception
End Try
End Using
Example 4 - The same as example 3 but the Try/Catch is within the Using - does this make a difference?
Using cn As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand
Try
With cmd
.Connection = cn
.Connection.Open()
.CommandText = "dbo.GetCustomerByID"
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using
Example 5 - The same as example 4 but the CommandText and cn are specified in the Using Statement - What advantage does this have?
Using cn As New SqlConnection(ConnectionString)
Using cmd As New SqlCommand("GetCustomerByID", cn)
Try
With cmd
.Connection.Open()
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using
Example 6 - The same as example 5 but the connection is opened on cn instead of cmd. Is it better to open the connection on cmd if only one stored procedure is to be executed?
Using cn As New SqlConnection(ConnectionString)
cn.Open()
Using cmd As New SqlCommand("GetCustomerByID", cn)
Try
With cmd
.Connection = cn
.CommandType = CommandType.StoredProcedure
.Parameters.Add("#CustomerID", SqlDbType.Int, 4)
.Parameters("#CustomerID").Value = CustomerID
End With
da = New SqlDataAdapter(cmd)
da.Fill(ds, "Customer")
Catch ex As Exception
End Try
End Using
End Using
The DataAdapter.Fill command will open and close the connection itself, so you don't need the cmd.Connection.Open(). (Ref: the remarks section in http://msdn.microsoft.com/en-us/library/377a8x4t.aspx .)
Using Using for the SqlConnection has the effect of calling .Close on it for you.
The variable cmd becomes eligible for garbage collection once it is out of scope (or earlier if .NET determines it isn't going to be used again).
In your example 2, I'm not sure it's such a good idea to dispose of the cmd before the DataAdapter has used it.
[Information from user "JefBar Software Services" in Should I call Dispose on a SQLCommand object? ] At the time of writing, calling .Dispose on an SqlCommand has no effect because of the code in its constructor:
public SqlCommand() : base() {
GC.SuppressFinalize(this);
}