Possible to have multiple SqlCommand? - sql

Dim conn As New SqlConnection("Database=Clinic_Management_System;Data Source=.\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|Clinic Management System.mdf")
Dim cmd As SqlCommand
Dim dr As SqlDataReader
conn.Open()
cmd = New SqlCommand("INSERT INTO record([PatientID],[Prescription],[VisitDate]) Values ('" & PatientIDTextBox.Text & "','" & txtPrescription.Text & "',GetDate()) ", conn)
cmd.ExecuteNonQuery()
For cn As Integer = 0 To DataGridView1.RowCount - 1
cmd = New SqlCommand("INSERT INTO record_item([RecordID],[ItemID],[Amount]) Values ( (SELECT MAX(RecordID) FROM record)," & DataGridView1.Rows(cn).Cells(0).Value & "," & DataGridView1.Rows(cn).Cells(2).Value & ")", conn)
cmd.ExecuteNonQuery()
Next
conn.Close()
Is this possible to run 2 SqlCommand together??
Because after executed somehow the 2nd inside the loop did not execute or insert data.

You don't have 2 SqlCommands.
You have 1 SqlCommand, called cmd, which is executed multiple times.
It is fine to do something like this, however I would have 1 SqlCommand for your INSERT INTO record, and 1 for your INSERT INTO record_item. I think this makes it much easier to understand when looking back at the code at a later date.
Either way, using a SqlCommand like this should not prevent it from executing, therefore I believe there is another issue with your scripting.
I've adapted your code so that it is split into 2 seperate SqlCommand objects, and the queries have been parameterized to prevent SQL Injection:
Dim conn As New SqlConnection("Database=Clinic_Management_System;Data Source=.\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|Clinic Management System.mdf")
Dim cmdRecord As New SqlCommand("INSERT INTO record ([PatientID],[Prescription],[VisitDate]) Values (#PatientID, #Prescription, GETDATE())", conn)
cmdRecord.Parameters.Add("#PatientID", SqlDbType.Int).Value = PatientIDTextBox.Text
cmdRecord.Parameters.Add("#Prescription", SqlDbType.NVarChar).Value = txtPrescription.Text
Dim cmdRecordItem As New SqlCommand("INSERT INTO record_item([RecordID],[ItemID],[Amount]) Values ( (SELECT MAX(RecordID) FROM record),#ItemID,#AmountID)", conn)
cmdRecordItem.Parameters.Add("#ItemID", SqlDbType.Int)
cmdRecordItem.Parameters.Add("#Amount", SqlDbType.Decimal)
Dim dr As SqlDataReader
conn.Open()
cmdRecord.ExecuteNonQuery()
For cn As Integer = 0 To DataGridView1.RowCount - 1
cmdRecordItem.Parameters("#ItemID").Value = DataGridView1.Rows(cn).Cells(0).Value
cmdRecordItem.Parameters("#Amount").Value = DataGridView1.Rows(cn).Cells(2).Value
cmdRecordItem.ExecuteNonQuery()
Next
conn.Close()

One command can only be used once.
If you want to use more than one command, declare a new cmd as
Dim cmd2 as SqlCommand

In order to ensure that either all statements complete successfully or that none do, you need to wrap your commands in a transaction.
Using parameters for the commands will also make the code more understandable and safer and you should use using statements where possible.
Also, performing the Select max recordid is a very bad idea (if you have multiple users), but I'll leave that for another time:
Using conn As New SqlConnection("Database=Clinic_Management_System;Data Source=.\SQLExpress;Integrated Security=True;AttachDBFilename=|DataDirectory|Clinic Management System.mdf")
Dim cmdRecord As SqlCommand
Dim cmdRecordItem As SqlCommand
Dim oTran As SqlTransaction = Nothing
conn.Open()
Try
cmdRecord = New SqlCommand("INSERT INTO record([PatientID],[Prescription],[VisitDate]) Values (#PatientID, #Prescription, GetDate())", conn)
cmdRecord.Parameters.AddWithValue("#PatientID", PatientIDTextBox.Text)
cmdRecord.Parameters.AddWithValue("#Prescription", txtPrescription.Text)
cmdRecordItem = New SqlCommand("INSERT INTO record_item([RecordID],[ItemID],[Amount]) SELECT ISNULL(MAX(RecordID), 0), #ItemID, #Amount FROM record", conn)
cmdRecordItem.Parameters.Add("#ItemId")
cmdRecordItem.Parameters.Add("#Amount")
oTran = conn.BeginTransaction
cmdRecord.ExecuteNonQuery()
For Each oRow As DataGridViewRow In DataGridView1
cmdRecordItem.Parameters("#ItemId").Value = oRow.Cells(0).Value
cmdRecordItem.Parameters("#Amount").Value = oRow.Cells(2).Value
cmdRecordItem.ExecuteNonQuery()
Next
oTran.Commit()
Catch
If oTran IsNot Nothing Then
oTran.Rollback()
End If
Throw
Finally
conn.Close()
End Try
End Using

Related

How to use oledbconnection in vb.net

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

Vb.Net 2010 - SQL Insert Command with autonumeric value

I'm looking to add a row with an autonumeric value using SQL.
I'm using Studio VB 2010. I have a very simple table with 2 fields:
ID Autonumeric
Model Text field.
constr = "INSERT INTO procedures VALUES('" & txtFName.Text & "')"
cmd = New OleDbCommand(constr, cn)
cn.Open()
Me.i = cmd.ExecuteNonQuery
A message says a parameter is missing,
so my question is...
How can I add in the SQL command this automatic value? (ID)
Should I get the last ID number and +1 ?? I think there's gotta be a simple way to do it.
Thank you.
Update #1
I am now trying parameterized queries as suggested...
I found this example,
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.Add("#a1", OleDbType.Integer).Value = 0
.Add("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
But still, I'm geting a Syntaxis error.
Any thoughts?
Thanks to you all.
UPDATE #2
This code seems to work if I give the next ID number, but again, how can I do it automatically?
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#a1", OleDbType.Integer).Value = 3
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
Any comments? Thanks again.
UPDATE #3 This Code gives me Syntaxis Error
I just put my only one column to update, the second one is the autonumber column, as I was told to try.
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO procedures (procedure) VALUES ('Model')"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
Try
Con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try
UPDATE #4 - SOLUTION
I'm putting this code in here in case someone finds it useful.
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;"
dbSource = "Data Source = c:\gastrica\dabase.accdb"
Con.ConnectionString = dbProvider & dbSource
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO [procedures] ([procedure]) VALUES (?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#procedure", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
Dim varProcedure As String = cmd.Parameters("#procedure").Value.ToString()
MessageBox.Show("Record inserted successfully. Procedure = " & varProcedure)
Catch ex As Exception
Throw ex
Finally
Con.Close()
End Try
Thanks all for your comments and help.
You need to specify the columns:
INSERT INTO procedures (columnname, columnname2) VALUES ('test', 'test');
Here is a sql fiddle showing an example:
http://sqlfiddle.com/#!9/3cf706/1
Try this one:
constr = "INSERT INTO procedures (ID, Model) VALUES (0,'" & txtFName.Text & "')"
'or (not sure)
constr = "INSERT INTO procedures (Model) VALUES ('" & txtFName.Text & "')"
When use 0 as value, in autonumeric fields SQL insert the next number
Thanks for your answers.
I couldnĀ“t do it, it gives me errors. So I end up with a single variable reaching the next Auto Value. Using a simple SQL command.
And then, everything runs good.
vNextAuto = GetDB_IntValue("SELECT TOP 1 * FROM procedures ORDER BY ID DESC", "ID") + 1
Dim SQL_command As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#id", OleDbType.Integer).Value = vNextAuto
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
'Dim id As String = cmd.Parameters("#id").Value.ToString()
'MessageBox.Show("Record inserted successfully. ID = " & id)
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try

.NET OleDb parameterized query not working as expected

I'm trying to pass this Update command to a database, it completes ok with no errors but it doesnt update the database and I can't understand why?
Dim Cmd As OleDbCommand
Dim SQL As String
Dim objCmd As New OleDbCommand
Dim Con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Settings.MasterPath)
Dim Item = "08/08/2015"
SQL = ("UPDATE [Hol Dates] SET [" & EmployeeList.Text & "]= #Htype WHERE [HDate]=#Hdate")
Cmd = New OleDbCommand(SQL, Con)
objCmd = New OleDbCommand(SQL, Con)
objCmd.Parameters.AddWithValue("#Hdate", item)
objCmd.Parameters.AddWithValue("#Htype", "None")
Con.Open()
Dim ans = MsgBox("Do you want to unbook this holiday?", MsgBoxStyle.YesNo)
If ans = MsgBoxResult.Yes Then
objCmd.ExecuteNonQuery()
Else
Exit Sub
End If
Con.Close()
Con.Dispose()
You need to reverse the order in which you add the parameters to the OleDbCommand object. OleDb allows us to assign names to parameters but it ignores the names and only pays attention to the order in which the parameters appear in the CommandText.
Therefore, since your SQL statement refers to Htype and then Hdate you need to add the parameters in that same order.

Execute a SQL Stored Procedure and process the results [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In VB.NET, how do I do the following?
Execute a Stored Procedure
Read through the DataTable returned
At the top of your .vb file:
Imports System.data.sqlclient
Within your code:
'Setup SQL Command
Dim CMD as new sqlCommand("StoredProcedureName")
CMD.parameters("#Parameter1", sqlDBType.Int).value = Param_1_value
Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
CMD.CommandType = CommandType.StoredProcedure
Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300
'Fill the dataset
Dim DS as DataSet
adapter.Fill(ds)
connection.Close()
'Now, read through your data:
For Each DR as DataRow in DS.Tables(0).rows
Msgbox("The value in Column ""ColumnName1"": " & cstr(DR("ColumnName1")))
next
Now that the basics are out of the way,
I highly recommend abstracting the actual SqlCommand Execution out into a function.
Here is a generic function that I use, in some form, on various projects:
''' <summary>Executes a SqlCommand on the Main DB Connection. Usage: Dim ds As DataSet = ExecuteCMD(CMD)</summary>'''
''' <param name="CMD">The command type will be determined based upon whether or not the commandText has a space in it. If it has a space, it is a Text command ("select ... from .."),'''
''' otherwise if there is just one token, it's a stored procedure command</param>''''
Function ExecuteCMD(ByRef CMD As SqlCommand) As DataSet
Dim connectionString As String = ConfigurationManager.ConnectionStrings("main").ConnectionString
Dim ds As New DataSet()
Try
Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
'Assume that it's a stored procedure command type if there is no space in the command text. Example: "sp_Select_Customer" vs. "select * from Customers"
If CMD.CommandText.Contains(" ") Then
CMD.CommandType = CommandType.Text
Else
CMD.CommandType = CommandType.StoredProcedure
End If
Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300
'fill the dataset
adapter.Fill(ds)
connection.Close()
Catch ex As Exception
' The connection failed. Display an error message.
Throw New Exception("Database Error: " & ex.Message)
End Try
Return ds
End Function
Once you have that, your SQL Execution + reading code is very simple:
'----------------------------------------------------------------------'
Dim CMD As New SqlCommand("GetProductName")
CMD.Parameters.Add("#productID", SqlDbType.Int).Value = ProductID
Dim DR As DataRow = ExecuteCMD(CMD).Tables(0).Rows(0)
MsgBox("Product Name: " & cstr(DR(0)))
'----------------------------------------------------------------------'
From MSDN
To execute a stored procedure returning rows programmatically using a command object
Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
someVar = reader(0)
someVar2 = reader(1)
someVar3 = reader("NamedField")
End If
sqlConnection1.Close()
Simplest way? It works. :)
Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
Try
Using connection As New SqlConnection(ConnStrg)
connection.Open()
Dim command As New SqlCommand(queryString, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim DTResults As New DataTable
DTResults.Load(reader)
MsgBox(DTResults.Rows(0)(0).ToString)
End Using
Catch ex As Exception
MessageBox.Show("Error while executing .. " & ex.Message, "")
Finally
End Try
Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
Dim adapter As System.Data.SqlClient.SqlDataAdapter
Dim dsdetailwk As New DataSet
Try
adapter = New System.Data.SqlClient.SqlDataAdapter
adapter.SelectCommand = cmd
adapter.Fill(dsdetailwk, "delivery")
Catch Err As System.Exception
End Try
sqlConnection1.Close()
datagridview1.DataSource = dsdetailwk.Tables(0)
My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code
Please make sure that your procedure return some rows
Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
Try
Connection.Connect()
debug.print("Look up account number " & AccountNumber)
Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
Dim DST As New DataSet
DP.Fill(DST)
Return DST.Tables(0)
Catch ex As Exception
Return Nothing
End Try
End Function

Insert new records into a table with Visual Basic using OLEDBConnection

I'm using Visual Basic 2010 Express and Access 2003.
I'm trying to make sql querys to the mdb file. I'm using OLEDBConnection. The Select query works fine, but I can't insert rows in the table. Here is the code.
Dim connStr As String = "provider=Microsoft.Jet.OLEDB.4.0;data source=" & System.IO.Directory.GetCurrentDirectory() & "\tpv.mdb;"
Dim con As New OleDb.OleDbConnection(connStr)
con.Open()
Dim query As String = "select * from Productos"
Dim cmd As New OleDb.OleDbCommand(query, con)
Dim reader As OleDb.OleDbDataReader
reader = cmd.ExecuteReader
While reader.Read()
MsgBox(reader.GetValue(0) & ", " & reader.GetValue(1) & " , " & reader.GetValue(2))
End While
reader.Close()
query = "insert into Productos (NombreProducto,PrecioCoste) VALUES ('cana',4)"
Dim cmd2 As New OleDb.OleDbCommand(query, con)
cmd.ExecuteNonQuery()
con.Close()
Why the INSERT query does not work?
Ok, I found my stupid problem.
Althoug I have declared 2 OleDbCommands, I referenced the first one in both cases