I should change all queries to use parameters to protect app from SQL injection.
Current insert sample which works is:
If Len(ExecuteQuery("INSERT INTO ICE_Order_Details(Order_ID, Product_ID, License_Type_ID, Maintenance_ID, Qty, Shareit_Running_No, Price, Total) VALUES(" & OrderID & ", " & ProductID & ", " & LicenseTypeID & ", " & MaintenanceID & ", " & Val(Request("QUANTITY")) & ", " & Val(Request("RUNNING_NO")) & ", " & Price & ", " & Price * Val(Request("QUANTITY")) & ")")) > 0 Then
'SendBadRequest "Could not run insert Order detail query"
Can you help me to write parametric query instead of this?
I tried a lot of ways to do this but here is below last one.
Dim ConnString As New SqlConnection("Provider=SQLOLEDB.0;Data Source=something;Initial Catalog=something;Persist Security Info=True;User ID=something;Password=something")
Dim SqlString As String ="INSERT INTO ICE_Order_Details(Order_ID, Product_ID, License_Type_ID, Maintenance_ID, Qty, Shareit_Running_No, Price, Total) VALUES(#OrderID, #ProductID, #LicenseTypeID, #MaintenanceID, #Qty, #RunningNo, #Price, #Total)"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#OrderID", OrderID)
cmd.Parameters.AddWithValue("#ProductID", ProductID)
cmd.Parameters.AddWithValue("#LicenseTypeID", LicenseTypeID)
cmd.Parameters.AddWithValue("#MaintenanceID", MaintenanceID)
cmd.Parameters.AddWithValue("#Qty", Val(Request("QUANTITY")))
cmd.Parameters.AddWithValue("#RunningNo", Val(Request("RUNNING_NO")))
cmd.Parameters.AddWithValue("#Price", Price)
cmd.Parameters.AddWithValue("#Total", Price * Val(Request("QUANTITY")))
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Edit: It still doesn't work. Here is my current code for adding parameters:
cmd.Parameters.Add("#OrderID", SqlDbType.Int).Value = OrderId
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = ProductID
cmd.Parameters.Add("#LicenseTypeID", SqlDbType.Int).Value = LicenseTypeID
cmd.Parameters.Add("#MaintenanceID", SqlDbType.Int).Value = MaintenanceID
cmd.Parameters.Add("#Qty", SqlDbType.Int).Value = Int32.Parse(Request("QUANTITY"))
cmd.Parameters.Add("#RunningNo", SqlDbType.Int).Value = Int32.Parse(Request("RUNNING_NO"))
cmd.Parameters.Add("#Price", SqlDbType.Money).Value = Money.Parse(Price)
cmd.Parameters.Add("#Total", SqlDbType.Money).Value = Money.Parse(Price * Int32.Parse(Request("QUANTITY")))
Edit: I changed my insert query to test only insert with parameters. But it don't work
Dim ConnString As String = ConfigurationManager.ConnectionStrings("DB_Connection_String0").ConnectionString
Dim SqlString As String ="INSERT INTO Unsubscribed(E-Mail) VALUES(#E-Mail)"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#E-Mail", SqlDbType.nvarchar).Value = "testiram#obrisime.sada"
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
here is error which i got (it marked 'As') if I change connection string it show error on next 'As' in code with same error message
Microsoft VBScript compilation error '800a0401'
Expected end of statement
/Test.asp, line 8
Dim ConnString As String =
ConfigurationManager.ConnectionStrings("DB_Connection_String0").ConnectionString
---------------^
Finally I found solution for this
Thanks all for help!
here is code below which work fine
<%
Dim oConn, oCmd, ds, sql
p1 = "test"
p2 = "test"
p3 = "test"
ds = "Provider=SQLOLEDB.1;Data Source=___;Initial Catalog=___;User ID=___;Password=___;"
sql = "INSERT INTO table (prop1, prop2, prop3) VALUES (?,?,?)"
Set oConn=Server.CreateObject("ADODB.Connection")
oConn.Open ds
Set oCmd = Server.CreateObject("ADODB.Command")
oCmd.ActiveConnection = oConn
oCmd.CommandText = sql
oCmd.CommandType = 1
oCmd.Parameters(0) = p1
oCmd.Parameters(1) = p2
oCmd.Parameters(2) = p3
oCmd.Execute()
oConn.close
Set oConn=nothing
%>
it is better to use sqlhelper class file by microsoft which i think is best for this cause and is relatively easy to use and shortens code by much. e.g
in save click event it will go like this
sqlParameter[] parem=
{
new sqlparameter("#value1"urcontrol.text),
new sqlparameter("#value2"urcontrol.text),
new sqlparameter("#value3"urcontrol.text)
};
sqlhelper.executenonquery (connectionstring,commandtype.storeprocedure,"ProcedureName",parem);
rest will be handled automatically by sqlhelper class file
Related
How would I create a query that returns a column in the database? The SQL select statement is easy. I'm having issues with the VB side.
SELECT UserNO
FROM UserTable
WHERE UserID = user;
I need to then get that UserNO and pass it to another T-SQL stored procedure. How would I go about running a SELECT query and getting the results back in Visual Basic?
Attached is some of my code. The code below adds the user to the DB however the UserNo (INTEGER) is automatically generated by SQL Server as the INSERT statement is run in the insert stored procedure, so I need to pull the UserNO after the user is created.
Public conwd As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")
Public conwp As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")
Dim cmdP As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwp)
Dim cmdD As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwd)
conmp.Open()
conmd.Open()
cmdP.ExecuteNonQuery()
cmdD.ExecuteNonQuery()
The Using..End Using blocks close and dispose of your data objects that might contain unmanaged code. The Parameters help prevent SQL injection.
Private Sub OPCode2()
Dim newID As Integer
Dim sql = "Insert Into UserTable (User) Values (#User); Select SCOPE_IDENTITY();"
Using cn As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#User", SqlDbType.NVarChar).Value = "Brian Weaver"
cn.Open()
newID = CInt(cmd.ExecuteScalar)
End Using
End Using
'Use the newID in your next command
UserStoredProcedure(newID)
End Sub
Private Sub UseStoredProcedure(id As Integer)
Dim sql = "InsertSomeUserInfo" 'the name of your stored procedure
Using cn As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand(sql, cn)
cmd.CommandType = CommandType.StoredProcedure
'whatever parameter names and types your stored procedure uses
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = id
cmd.Parameters.Add("#Salary", SqlDbType.Decimal).Value = 50000
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Dim cmdP As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'" + "; SELECT CAST(scope_identity() AS int", conwp)
Dim userNo as Integer = cmdP.ExecuteScalar()
ExecuteScalar retrieves the first line of the result
Currently trying to update an SQL Server database from an Access db, it works importing new records but fails on when I reimport the file and there is a duplicate - in looking for it to insert the row if it's not there (working), but skip if it already exists. The first column has the primary key set.
Dim table As DataTable = New DataTable
Dim accConnection As New OleDb.OleDbConnection(
"Provider=Microsoft.JET.OLEDB.4.0; Data Source='C:\Tester.mdb';User Id=admin; Password=;")
Dim sqlConnection As New SqlClient.SqlConnection(
"Data Source=10.75.24.94;Initial Catalog=CTData;User ID=sql;Password=")
Try
'Import the Access data
accConnection.Open()
Dim accDataAdapter = New OleDb.OleDbDataAdapter(
"SELECT * FROM Import_test", accConnection)
accDataAdapter.Fill(table)
accConnection.Close()
'Export to MS SQL
For Each row As DataRow In table.Rows
row.SetAdded()
Next
sqlConnection.Open()
Dim sqlDataAdapter As New SqlClient.SqlDataAdapter(
"SELECT * FROM Import_test", sqlConnection)
Dim sqlCommandBuilder As New SqlClient.SqlCommandBuilder(sqlDataAdapter)
sqlDataAdapter.InsertCommand = sqlCommandBuilder.GetInsertCommand()
sqlDataAdapter.UpdateCommand = sqlCommandBuilder.GetUpdateCommand()
sqlDataAdapter.DeleteCommand = sqlCommandBuilder.GetDeleteCommand()
sqlDataAdapter.Update(table)
sqlConnection.Close()
Catch ex As Exception
If accConnection.State = ConnectionState.Open Then
accConnection.Close()
End If
If sqlConnection.State = ConnectionState.Open Then
sqlConnection.Close()
End If
MessageBox.Show("Import failed with error: " &
Environment.NewLine & Environment.NewLine &
ex.ToString)
End Try
The error I'm presented with is:
Violation of Primary key. Cannot insert duplicate key in object.
I think you can remove VB from the equation (I like to make things as simple as possible, without over-simplifying it). You have several options available.
INSERT INTO Table
SELECT * FROM #Table xx
WHERE NOT EXISTS (SELECT 1 FROM Table rs WHERE rs.id = xx.id)
Or . . .
DELETE FROM Table
WHERE (ID NOT IN (SELECT MAX(ID) AS Expr1
FROM Table
AS Table_1 GROUP BY NAME,ADDRESS,CITY,STATE,ZIP,PHONE,ETC.))
There are a lot of other ways to handle this as well. Is you need to incorporate VB, you can do something like this.
Dim cmd As New OleDbCommand
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\your_path\DB.accdb")
Dim queryResult As Integer
Dim sqlQRY As String = "SELECT COUNT(*) AS FROM ESRRegister WHERE ID = '" & IDtxt.Text & "'"
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.Text
If queryResult > 0 Then
cmd.CommandText = "insert into ESRRegister (Dt,ID)VALUES ('" & Dttxt.Text & "' , '" & IDtxt.Text & "')"
queryResult = cmd.ExecuteScalar()
MsgBox("Added Successfuly")
Else
MessageBox.Show("Already Exists!", "ALI ENTERPRISES", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
what I want to do is after I select the name from the dropdown list, the details which are related with the user can pop up in the textboxes. I created a view at sql alreaday called VEditUser. But after I run the code, try catch always tell incorrect syntax near " = ". Can somebody tell me where is wrong?
Dim MyConnection As New SqlConnection
Dim Command As New SqlCommand
Dim Datareader As SqlDataReader
Try
'Create a connection to the SQL server
MyConnection.ConnectionString = "server=(local);database=dbSQL1;Trusted_Connection=yes"
MyConnection.Open()
Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser = " & ddlCustomer.SelectedValue
Command.Connection = MyConnection
Datareader = Command.ExecuteReader
Try
If Datareader.HasRows Then
Datareader.Read()
txtFirstName.Text = Datareader.Item("strFirstName")
txtLastName.Text = Datareader.Item("strLastName")
txtAddress.Text = Datareader.Item("strAddress")
txtCity.Text = Datareader.Item("strCity")
dpdState.Text = Datareader.Item("intStateID")
txtZipcode.Text = Datareader.Item("strZipcode")
txtEmail.Text = Datareader.Item("strEmail")
txtCellPhone.Text = Datareader.Item("strCellPhone")
dpdServiceGroup.Text = Datareader.Item("intServiceGroupID")
dpdRole.Text = Datareader.Item("intRoleID")
dpdStatus.Text = Datareader.Item("intStatusID")
txtUserName.Text = Datareader.Item("strLoginName")
End If
Catch ex As Exception
End Try
MyConnection.Close() 'Close the connection.
The quick answer is that you are missing the where from your Sql:
change:
Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser = " & ddlCustomer.SelectedValue
to
Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser WHERE strLoginName = " & ddlCustomer.SelectedValue
For example. If strLoginName is not the value in the dropdown then replace as appropriate
The slightly longer answer is that you should be protecting yourself from Sql Injection by always sanitising your inputs, and using parameterized queries. In the example you have provided you can achieve this by using the following:
Command.CommandText = "SELECT strFirstName, strLastName, strAddress, strCity, intStateID, strZipcode, strEmail, strCellPhone, intServiceGroupID, intRoleID, intStatusID, strLoginName FROM VEditUser WHERE strLoginName = #customer"
cmd.Parameters.Add("#customer", SqlDbType.VarChar, 50).Value = ddlCustomer.SelectedValue
Command.Connection = MyConnection
So basically, the problem I am having is that I change values fine and when clicking the amend button is gives no errors and updates the shown DataGridView fine. However it is not actually updating the Access database. Meaning if the program is closed or whatever and reopened the values go back to the original ones the program gets from the database. Clearly showing it is not being updated.
Dim dsConnectionM As OleDb.OleDbConnection
Dim dsConnectionL As OleDb.OleDbConnection
Dim dsConnectionE As OleDb.OleDbConnection
Dim dsDataAdapterM As OleDbDataAdapter
Dim dsDataAdapterL As OleDbDataAdapter
Dim dsDataAdapterE As OleDbDataAdapter
Dim dsDataSetM As DataSet
Dim dsDataSetL As DataSet
Dim dsDataSetE As DataSet
Public Sub dsLoadMembers()
dsConnectionM = New OleDbConnection
dsConnectionM.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data source=DataSourceDB.accdb"
dsDataAdapterM = New OleDbDataAdapter
dsDataAdapterM.SelectCommand = New OleDbCommand
dsDataAdapterM.SelectCommand.Connection = dsConnectionM
dsDataAdapterM.SelectCommand.CommandText = "SELECT * FROM Member"
dsDataAdapterM.SelectCommand.CommandType = CommandType.Text
dsConnectionM.Open()
dsDataSetM = New DataSet
dsDataAdapterM.Fill(dsDataSetM, "dataSetMembers")
dsConnectionM.Close()
Form3.dgdMembers.AutoGenerateColumns = True
Form3.dgdMembers.DataSource = dsDataSetM
Form3.dgdMembers.DataMember = "dataSetMembers"
End Sub
Public Sub AmendMember()
Form3.dgdMembers.Rows(Form3.m).Cells("MemberID").Value = Form3.tbid.Text
Form3.dgdMembers.Rows(Form3.m).Cells("Forename").Value = Form3.tbfn.Text
Form3.dgdMembers.Rows(Form3.m).Cells("Surname").Value = Form3.tbsn.Text
Form3.dgdMembers.Rows(Form3.m).Cells("DOB").Value = Form3.dtpdob.Value
Form3.dgdMembers.Rows(Form3.m).Cells("Section").Value = Form3.tbsr.Text
Form3.dgdMembers.Rows(Form3.m).Cells("Postcode").Value = Form3.tbpc.Text
Form3.dgdMembers.Rows(Form3.m).Cells("HomeTel").Value = Form3.tbht.Text
Form3.dgdMembers.Rows(Form3.m).Cells("MobileTel").Value = Form3.tbmt.Text
Form3.dgdMembers.Rows(Form3.m).Cells("AddressLine1").Value = Form3.tbal1.Text
Form3.dgdMembers.Rows(Form3.m).Cells("AddressLine2").Value = Form3.tbal2.Text
Form3.dgdMembers.Rows(Form3.m).Cells("City").Value = Form3.tbc.Text
Form3.dgdMembers.Rows(Form3.m).Cells("EmailAddress").Value = Form3.tbea.Text
Form3.dgdMembers.Rows(Form3.m).Cells("P/GForename").Value = Form3.tbpgfn.Text
Form3.dgdMembers.Rows(Form3.m).Cells("P/GSurname").Value = Form3.tbpgsn.Text
dsConnectionM.Open()
dsDataAdapterM.Update(dsDataSetM, "dataSetMembers")
dsDataSetM.AcceptChanges()
dsConnectionM.Close()
End Sub
First of all, check that your data source is the full path of the database.
Also, there is any easier way to update a database; you can use an UPDATE statement to do it.
In my public class I have the following declared:
Dim provider As String
Dim datafile As String
Dim connString As String
Dim myconnection As OleDbConnection = New OleDbConnection
Now for the actual example of code:
myconnection.open()
dim variable as string
variable = "UPDATE tablename SET columnname = value WHERE (enter criteria )"
Dim cmd as oledbcommand = New oledbcommand(variable, myconnection)
cmd.ExecuteNonQuery()
myconnection.close()
So for your code:
Public Sub AmendMember()
myconnection.open()
variable = "UPDATE dataSetMembers SET MemberID = '" & Form3.tbid.text &"', Forename = '" & Form3.tbfn.Text &"', Surname = '" & Form3.tbsn.Text &"', DOB = '" & Form3.dtpdob.text &"', Section = '" & Form3.tbsr.Text &"', Postcode = '" & Form3.tbpc.Text &"', HomeTel = '" & Form3.tbht.Text &"', MobileTel = '" & Form3.tbmt.Text &"', AddressLine1 = '" & Form3.tbal1.Text &"', AddressLine2 = '" & Form3.tbal2.Text &"', City = '" & Form3.tbc.Text &"', EmailAddress = '" & Form3.tbea.Text &"', P/GForename = '" & Form3.tbpgfn.Text &"', P/GSurname = '" & Form3.tbpgsn.Text &" "
Dim cmd as oledbcommand = New oledbcommand(variable, myconnection)
cmd.ExecuteNonQuery()
myconnection.close()
End Sub
In this I have assumed the name of your table from your previous code.
I write a sql statement into vb.net to fetch data from msaccess where date equal to patepicker control. But here syntax error.
My code given below:-
Dim ct As String = "select * from add_student where _Date <= #" & dtDate1.ToString("MM/dd/yyyy") & "#"
cmd = New OleDbCommand(ct)
cmd.Connection = con
rdr = cmd.ExecuteReader()
Note:- _Date column had Date/Time Data type in ms access database
Please suggest me, Where is mistake
You should always use parameters:
dim sqlQuery ="Select * from add_student where _Date = ?"
using conn = New OleDbConnection("connectionstring")
conn.open()
Using selectCmd As New OleDbCommand(sqlQuery, conn)
selectCmd.Parameters.Add("_Date", OleDbType.Date).Value = dtDate1
using rdr = selectCmd.ExecuteReader()
while rdr.read()
End While
End Using
End Using
End Using
Your issue may be that "/" is not a slash but the localized date separator.
Thus, force slashes:
Dim ct As String = "select * from add_student where _Date <= #" & dtDate1.ToString("MM'/'dd'/'yyyy") & "#"
and perhaps brackets for the weird field name:
Dim ct As String = "select * from add_student where [_Date] <= #" & dtDate1.ToString("MM'/'dd'/'yyyy") & "#"