Executing two cmd.commandtext in one line - vb.net

The program executes one cmd.commandtext at a time. Both of my tables are using the same primary keys which is ID.
How do I execute both cmd.commandtext at the same time?
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim cnnOLEDB As New OleDbConnection
Dim cmdInsert As New OleDbCommand
Dim cmdOLEDB As New OleDbCommand
Dim cmdUpdate As New OleDbCommand
Dim connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Harry\Documents\Database1.accdb;"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cnnOLEDB.ConnectionString = connection
cnnOLEDB.Open()
End Sub
Private Sub btnReal_Click(sender As Object, e As EventArgs) Handles btnReal.Click
If txtName.Text <> "" And txtId.Text <> "" And txtReceipt.Text <> "" Then
cmdUpdate.CommandText = "UPDATE customer Set Stu_Name = '" & txtName.Text & " ' " & "WHERE ID = " & txtId.Text & " ; "
cmdUpdate.CommandText = "UPDATE admin Set receipt = '" & txtReceipt.Text & " ' " & "WHERE ID = " & txtId.Text & " ; "
cmdUpdate.CommandType = CommandType.Text
cmdUpdate.Connection = cnnOLEDB
cmdUpdate.ExecuteNonQuery()
cmdUpdate.Dispose()
MsgBox(txtName.Text + "Record Updated!")
End If
End Sub

The first thing to say here is: Do not use string concatenation to build sql queries, but use always a parameterized query. Without it you will find a lot of problem like parsing of single quotes in your name or worst an Sql Injection hack. Said that, I suppose that you are using OleDb (probably with an Access database). This scenario doesn't support the execution of multiple command in a single sql statement.
You are forced to call the ExecuteNonQuery two times after changing the command text
Private Sub btnReal_Click(sender As Object, e As EventArgs) Handles btnReal.Click
If txtName.Text <> "" And txtId.Text <> "" And txtReceipt.Text <> "" Then
cmdUpdate.Connection = cnnOLEDB
cmdUpdate.CommandText = "UPDATE customer Set Stu_Name = #name " & _
"WHERE ID = #id"
cmdUpdate.Parameters.Add("#name", OleDbType.VarWChar).Value = txtName.Text
cmdUpdate.Parameters.Add("#id", OleDbType.Integer).Value = Convert.ToInt32(txtId.Text)
cmdUpdate.ExecuteNonQuery()
cmdUpdate.Parameters.Clear()
cmdUpdate.CommandText = "UPDATE admin Set receipt = #recpt " & _
"WHERE ID = #id"
cmdUpdate.Parameters.Add("#recpt", OleDbType.VarWChar).Value = txtReceipt.Text
cmdUpdate.Parameters.Add("#id", OleDbType.Integer).Value = Convert.ToInt32(txtId.Text)
cmdUpdate.ExecuteNonQuery()
End If
End Sub
Not strictly related to your actual problem, but it seems pretty clear from your code that you have a global connection object and also a global command object. Don't do that. You gain very little in terms of performance but you will have problems with disposing connection, keep track of open/closed state and you will consume precious system resources. Always use a local connection object inside a using statement.

Related

select case and error join multiple table

Imports System.Data.OleDb
Public Class Form1
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim strSQL As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnsearch.Click
Dim fieldselect As String = ""
Select Case ComboBox1.Text
Case "startYear"
fieldselect = "startYear"
Case "genres"
fieldselect = "genres"
Case "Rating"
fieldselect = "Rating"
End Select
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Movies.accdb; Persist Security Info=False;")
strSQL = "SELECT startYear, genres, averageRating FROM (basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst)" & fieldselect & "'" & TextBox1.Text & "%'"
conn.Open()
da = New OleDbDataAdapter(strSQL, conn)
Dim ds As New DataSet("Movies")
da.Fill(ds, "Movies")
DataGridView1.DataSource = ds.Tables("Movies")
conn.Close()
End Sub
Keep you data objects local so you can control there closing and disposing. Using...End Using blocks do this for you even it there is an error.
Are all your fields in the Select Case the same datatype? If not you will have to adjust the code. If you need help, tell me the datatypes so I can fix the code.
Always use parameters to avoid sql injection. A text box can hold a Drop Table command. Parameters are treated as values not executable code.
If you need to update later in the code, you will need to have a primary key available in your Select.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Since your field name exactly matches the combo text the Case statement is not necessary
Dim fieldselect As String = ComboBox1.Text
Dim dt As New DataTable
Using conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Movies.accdb; Persist Security Info=False;")
Dim strSQL = "SELECT startYear, genres, averageRating FROM basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst Where " & fieldselect & " = #FieldValue;"
Using cmd As New OleDbCommand(strSQL, conn)
cmd.Parameters.Add("#FieldValue", OleDbType.VarChar).Value = TextBox1.Text
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
i wanted to use combo box as the filter for my program, i need to filter data from 2 different table. rating has it own table and basic is different table. both of the field mention above does not have any connection.
It's a bit had to help without context but I gave it a try :
I would replace
strSQL = "SELECT startYear, genres, averageRating FROM (basic.tconst Inner JOIN Rating.tconst on basic.tconst=Rating.tconst)" & fieldselect & "'" & TextBox1.Text & "%'"
With
"SELECT startYear, genres, averageRating " &
"FROM basic.tconst " &
"INNER JOIN Rating.tconst on basic.tconst=Rating.tconst " & fieldselect & "'" & TextBox1.Text & "%'"
To get better help, could you explain how tables Rating and basic works and what fieldselect is ?

How to make log in code in vb.net

Hello Guys please help me about this code,
This is simple log in code in visual studio 2013, my problem is, i try to make wrong password and user name, but the message box does not shows, it means no event after the "else"
HERE IS MY CODE:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim dr As OleDbDataReader
Call OpenDB()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'")
cmd.Connection = conn
dr = cmd.ExecuteReader
If dr.HasRows = True Then
dr.Read()
If dr.Item("UserName") = txtTeacher.Text And dr.Item("UserPass") = txtPword.Text Then
frmMain.Show()
Me.Hide()
Else
MsgBox("You are not a Registered Teacher")
End If
End If
dr.Close()
frmMain.StatusStrip1.Items(0).Text = txtTeacher.Text
Call CloseDB()
End Sub
Your issue is that your query "SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'" does not return anything when you enter the wrong password, so it never even executes the code within the If dr.HasRows = True Then block.
Also, you should NEVER store passwords in plain text. Hash them. And, you should always use parameters to preclude SQL injection attacks.
So, you would want to change your code to something like this:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = #UserName AND UserPass = #HashedPassword")
cmd.Parameters.Add(New OleDbParameter("#UserName", txtTeacher.Txt))
cmd.Parameters.Add(New OleDbParameter("#HashedPassword", HasherFunction(txtPword.Txt)))
Note the addition of the parameters and also the HasherFunction which you would have to build to hash your password accordingly.
There are plenty of resources available about SQL injection and how to avoid it. Here's one I found at the top of the Google search: https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
you almost there in your code, just don't repeat the checking if the user exists in the database, and you code should be like this based on what you put in the question
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim dr As OleDbDataReader
Call OpenDB()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'")
cmd.Connection = conn
dr = cmd.ExecuteReader
If dr.HasRows = True Then
' you don't need to check again if the user and password are same since you made it
' in you query to database
frmMain.Show()
Me.Hide()
Else
MsgBox("You are not a Registered Teacher")
End If
dr.Close()
frmMain.StatusStrip1.Items(0).Text = txtTeacher.Text
Call CloseDB()
End Sub
hope it will help you

Retrieving/adding data from/to a stored procedure

Alright so I have this webpage that I have to create and it has 3 pages and a master page. Now basically all of it is working, except the fact that I can't seem to get data coming into the webpage when requested via a retrieve button, nor will it update or add data to the SQL table. Now in my queries page when I put Select * From Customer it brings back the data in the table so that part works. From what I have to work with in the pdf's provided, they want me to use
TextBox1.Text = table.Rows(0).Field<string>("TextBox1")
TextBox1.DataBind()
To retrieve the data from the sql, now it comes up with an error saying Overload resolution failed because no accessible 'Field' accepts this number of arguments.
So here is my Customer page
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data.DataRowCollection
Public Class Customer
Inherits System.Web.UI.Page
Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("dbConnection1").ConnectionString)
Shadows adapter As SqlDataAdapter = New SqlDataAdapter()
// Tells me to use Shadows because variable adapter conflicts with property 'adapter'
Dim table As DataTable = New DataTable()
Dim command As SqlCommand = New SqlCommand()
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
conn = New SqlConnection(ConfigurationManager.ConnectionStrings("dbConnection1").ConnectionString)
Dim command As SqlCommand = New SqlCommand()
command.Connection = conn
command.CommandType = CommandType.Text
command.CommandText = "INSERT INTO Acme_Customer VALUES(" & txtCustID.Text & ",'" & txtFirstname.Text & "', '" & txtSurname.Text & "', " & txtGender.Text & ", " + txtAge.Text & ", " & txtAddress1.Text & ", " & txtAddress2.Text & ", " & txtCity.Text & ", " + txtPhone.Text & ", " + txtMobile.Text & ", " & txtEmail.Text & ")"
command.Connection.Open()
adapter.InsertCommand = command
adapter.InsertCommand.ExecuteNonQuery()
command.Connection.Close()
Clear()
lblMessage.Text = "You have been successfully added into our records"
Catch ex As Exception
lblMessage.Text = "Something has gone wrong with adding you to our records, please double check everything as we want you to become a member."
End Try
End Sub
Protected Sub btnRetrieve_Click(sender As Object, e As EventArgs) Handles btnRetrieve.Click
Try
command.Connection = conn
command.CommandType = CommandType.StoredProcedure
command.CommandText = "GetCustomer"
command.Connection.Open()
Dim param As SqlParameter = New SqlParameter()
param.ParameterName = "#ID"
param.SqlDbType = SqlDbType.Int
param.Direction = ParameterDirection.Input
param.Value = txtCustID.Text
command.Parameters.Add(param)
adapter.SelectCommand = command
adapter.Fill(table)
txtFirstname.Text = table.Rows(0).Field<string>("Firstname")
txtFirstname.DataBind()
txtSurname.Text = table.Rows(0).Field<string>("Surname")
txtSurname.DataBind()
txtGender.Text = table.Rows(0).Field<String>("Gender")
txtGender.DataBind()
txtAge.Text = table.Rows(0).Field<Integer>("Age")
txtAge.DataBind()
txtAddress1.Text = table.Rows(0).Field<String>("Address1")
txtAddress1.DataBind()
txtAddress2.Text = table.Rows(0).Field<String>("Address2")
txtAddress2.DataBind()
txtCity.Text = table.Rows(0).Field<String>("City")
txtCity.DataBind()
txtPhone.Text = table.Rows(0).Field<Integer>("Phone Number")
txtPhone.DataBind()
txtMobile.Text = table.Rows(0).Field<Integer>("Mobile Number")
txtMobile.DataBind()
txtEmail.Text = table.Rows(0).Field<String>("Email")
txtEmail.DataBind()
Catch ex As Exception
lblMessage.Text = "The ID you have entered doesn't exist."
End Try
End Sub
So I'm just wondering what I've written wrong or if I should be using other code instead of what I have here, I know I should be using C# but I just got the hang of vb so, hopefully I can just start using C# after this project.
Protected Sub btnRetrieve_Click(sender As Object, e As EventArgs) Handles btnRetrieve.Click
Try
command.Connection = conn
command.CommandType = CommandType.StoredProcedure
command.CommandText = "GetCustomer"
command.Connection.Open()
Dim param As SqlParameter = New SqlParameter()
param.ParameterName = "#ID"
param.SqlDbType = SqlDbType.Int
param.Direction = ParameterDirection.Input
param.Value = txtCustID.Text
command.Parameters.Add(param)
adapter.SelectCommand = command
adapter.Fill(table)
dim objDV as dataview = table.defaultview
txtFirstname.Text = objDV(0)("Firstname").tostring
txtSurname.Text = objDV(0)("Surname").tostring
' Fill all other text boxes following above lines
Catch ex As Exception
lblMessage.Text = "The ID you have entered doesn't exist."
End Try
End Sub

vb.net cannot write Query to MSAccess file

i can access to local Access Database and i can add some data using Query, but it JUST shows its data when the program is alive. when I re-execute this program, i cannot see any previously added data and so do original Database file(SourceDB.mdb).
How can I save my data? Here is my code.
Imports System.Data.OleDb
Public Class UserForm
Private myConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=.\SourceDB.mdb"
Private mDbConn As OleDbConnection
Private Sub Button_Search_Click(sender As Object, e As EventArgs) Handles Button_Search.Click
Dim myAdapter As New OleDbDataAdapter("SELECT * FROM user WHERE u_name = '" + tBoxName.Text + "'", myConn)
Dim myDataTable As New DataTable
If tBoxName.Text = "" Then
MsgBox("Input name")
Else
myAdapter.Fill(myDataTable)
If myDataTable.Rows.Count > 0 Then
tBoxPhone.Text = myDataTable.Rows(0).Item("u_phone")
tBoxAddr.Text = myDataTable.Rows(0).Item("u_addr")
tBoxBName.Text = myDataTable.Rows(0).Item("u_bname")
tBoxBAccount.Text = myDataTable.Rows(0).Item("u_baccount")
tBoxEtc.Text = myDataTable.Rows(0).Item("u_comment")
Else
MsgBox("No Name in Table")
End If
End If
End Sub
Private Sub Button_OK_Click(sender As Object, e As EventArgs) Handles Button_OK.Click
Try
If lblAOE.Text = "Add" Then
Dim myAdapter As New OleDbDataAdapter("INSERT INTO user (u_name, u_phone, u_addr, u_bname, u_baccount, u_comment) VALUES ('" + _
tBoxName.Text + "', '" + tBoxPhone.Text + "', '" + tBoxAddr.Text + "', '" + tBoxBName.Text + _
"', '" + tBoxBAccount.Text + "', '" + tBoxEtc.Text + "')", myConn)
Dim myDataTable As New DataTable
myAdapter.Fill(myDataTable)
Button_Add.Visible = True
Button_Modify.Visible = True
Button_OK.Visible = False
ClearTextBoxes()
Button_Clear.Text = "비우기"
End If Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button_Delete_Click(sender As Object, e As EventArgs) Handles Button_Delete.Click
If MessageBox.Show("Sure Wanna delete data?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Cancelled")
Exit Sub
Else
Dim myAdapter As New OleDbDataAdapter("DELETE FROM user WHERE u_name = '" + tBoxName.Text + "'", myConn)
Dim myDataTable As New DataTable
myAdapter.Fill(myDataTable)
MsgBox("DELETED")
ClearTextBoxes()
End If
End Sub
Private Sub ClientForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.UserTableAdapter.Fill(Me.SourceDBDataSet.user)
Me.Text = "User Form"
End Sub
End Class
You are using a OleDbDataAdapter trying to execute an INSERT operation (or a DELETE one), but this is not how the OleDbDataAdapter works.
An OleDbDataAdapter uses the SELECT command to retrieve the records and, if defined, its InsertCommand property to update records of a dataset through the call to the OleDbDataAdapter.Update method. You are not in this situation and you have your values directly in the textboxes. You could simply use an OleDbCommand with the appropriate sql statement (and this is the same for your DELETE method)
Try to change your code to
Dim cmdText = "INSERT INTO [user] (u_name, u_phone, u_addr, u_bname, " & _
"u_baccount, u_comment) VALUES (?, ?, ?, ?,?,?)"
Dim cmd = New OleDbCommand(cmdText, myConn)
cmd.Parameters.AddWithValue("#p1",tBoxName.Text)
cmd.Parameters.AddWithValue("#p2",tBoxPhone.Text )
cmd.Parameters.AddWithValue("#p3",tBoxAddr.Text)
cmd.Parameters.AddWithValue("#p4",tBoxBName.Text)
cmd.Parameters.AddWithValue("#p5",tBoxBAccount.Text)
cmd.Parameters.AddWithValue("#p6",tBoxEtc.Text )
cms.ExecuteNonQuery()
I have changed your string concatenation to a more correct parameterized query to avoid Sql Injection and parsing problems in case one of your textbox values contains a single quote.
you use OleDbCommand class. you make class object and use ExecuteNonQuery for insert data
like
Dim o As OleDbCommand
o.Connection = con
o.CommandType = CommandType.Text
o.CommandText = "your Query"
o.ExecuteNonQuery()
and you should use try block
try
o.ExecuteNonQuery()
catch
end try

VB.NET SQL Server Insert - ExecuteNonQuery: Connection property has not been initialized

In the form load event, I connect to the SQL Server database:
Private Sub AddBook_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myConnection = New SqlConnection("server=.\SQLEXPRESS;uid=sa;pwd=123;database=CIEDC")
myConnection.Open()
End Sub
Here in the Insert event, I use the following code:
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Try
myConnection.Open()
myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")")
myCommand.ExecuteNonQuery()
MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
ClearBox()
Catch ex As Exception
MsgBox(ex.Message())
End Try
myConnection.Close()
End Sub
And It produces the following error:
ExecuteNonQuery: Connection property has not been initialized
Connection Assignment - You aren't setting the connection property of the SQLCommand. You can do this without adding a line of code. This is the cause of your error.
myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")", MyConnection)
Connection Handling - You also need to remove `MyConnection.Open' from your Load Handler. Just open it and close it in your Click Handler, as you are currently doing. This is not causing the error.
Parameterized SQL - You need to utilize SQL Parameters, despite the fact that you are not using a Stored Procedure. This is not the cause of your error. As Conrad reminded me, your original code dumps values straight from the user into a SQL Statement. Malicious users will steal your data unless you use SQL Parameters.
Dim CMD As New SqlCommand("Select * from MyTable where BookID = #BookID")
CMD.Parameters.Add("#BookID", SqlDbType.Int).Value = CInt(TXT_BookdID.Text)
You need to set the Connection property on the command:
myCommand.Connection = myConnection
Pretty much what the error message implies - the Connection property of the SqlCommand object hasn't been assigned to the connection you opened (in this case you called it myConnection).
Also, a word of advice here. Do some reading on sql parameters - doing sql concatenation from user input without any sanity checks is the way SQL injection attacks happen.
This is one way to do it:
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Try
myConnection.Open()
myCommand = New SqlCommand( _
"INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, " & _
" EnterDate, CatID, RackID, Amount) " & _
"VALUES(#bookCode, #bookTitle, #author, #publishingYear, #price, #enterDate, " & _
" #catId, #rackId, #amount)")
myCommand.Connection = myConnection
with myCommand.Parameters
.AddWithValue("bookCode", txtBookCode.Text)
.AddWithValue("bookTitle", txtTitle.Text)
.AddWithValue("author", txtAuthor.Text)
.AddWithValue("publishingYear", txtPublishYear.Text)
.AddWithValue("price", txtPrice.Text)
.AddWithValue("enterDate", txtEnterDate.Text)
.AddWithValue("catId", txtCategory.Text)
.AddWithValue("rackId", txtRack.Text)
.AddWithValue("amount", txtAmount.Text)
end with
myCommand.ExecuteNonQuery()
MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
ClearBox()
Catch ex As Exception
MsgBox(ex.Message())
End Try
myConnection.Close()
End Sub
Module Module1
Public con As System.Data.SqlClient.SqlConnection
Public com As System.Data.SqlClient.SqlCommand
Public ds As System.Data.SqlClient.SqlDataReader
Dim sqlstr As String
Public Sub main()
con = New SqlConnection("Data Source=.....;Initial Catalog=.....;Integrated Security=True;")
con.Open()
frmopen.Show()
'sqlstr = "select * from name1"
'com = New SqlCommand(sqlstr, con)
Try
com.ExecuteNonQuery()
'MsgBox("success", MsgBoxStyle.Information)
Catch ex As Exception
MsgBox(ex.Message())
End Try
'con.Close()
'MsgBox("ok", MsgBoxStyle.Information, )
End Sub
End Module
Please try to wrap the use of your connections (including just opening) inside a USING block. Assuming the use of web.config for connection strings:
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("web.config_connectionstring").ConnectionString)
Dim query As New String = "select * from Table1"
Dim command as New SqlCommand(query, connection)
Using connection
connection.Open()
command.ExecuteNonQuery()
End Using
And PARAMETERIZE anything user-entered.. please!