I'd like to use this code to verify if duplication occurs or not before saving the data to the database. How am I supposed to close the sqldatareader? (As what the error shows me)
con.ConnectionString = "Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True"
cmd.Connection = con
con.Open()
Dim theQuery As String = "SELECT * FROM Profile WHERE RollNo=#RollNo AND Name=#Name"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#RollNo", TextBox1.Text)
cmd1.Parameters.AddWithValue("#Name", TextBox2.Text)
Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
cmd.CommandText = "INSERT INTO Profile VALUES ('" & rollno & "' , '" & name & "' , '" & gender & "' , '" & address & "' , '" & phoneno & "' , '" & datereg & "' , '" & faculty & "' , '" & course & "' , '" & semester & "')"
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
i = cmd.ExecuteNonQuery()
End If
End Using
con.Close()
The error are referring to is because you must complete the execution of the data reader before you try to execute another command on the same connection.
Additionally there are some issues with your code:
It is strongly recommended you use and then dispose of SqlConnections as you use them, do not try to reuse these globally in your application. The ado.net SQL Server client library will handle connection pooling for you by default.
You need to use parameters with your insert just like you did on your select.
Do not to use AddWithValue when adding your parameters, instead use the constructor and also specify the sql data type. If RollNo is a number (like integer) then you should pass the value as an integer to your parameter. I assumed it was a string stored in a varchar.
Wrap all types that implement IDisposable in Using statements to ensure resources are always released. (In case any one wants to nitpick, no it is not required for SqlCommand in this case.)
Dim recordExists As Boolean
Using con As SqlConnection = New SqlConnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")
Using cmd As SqlCommand = New SqlCommand("SELECT RollNo FROM Profile WHERE RollNo=#RollNo AND Name=#Name", con)
cmd.Parameters.Add("#RollNo", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TextBox2.Text
con.Open()
Using reader As SqlDataReader = cmd.ExecuteReader()
recordExists = reader.HasRows
End Using
End Using
End Using
If recordExists Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
Using con As SqlConnection = New SqlConnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")
Using cmd As SqlCommand = New SqlCommand("INSERT INTO Profile (RollNo, Name) VALUES (#RollNo, #Name)", con)
cmd.Parameters.Add("#RollNo", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = TextBox2.Text
con.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
End Using
End Using
End If
if you are using using then not need to close. because it internally close all connection. The code would be like this
using(var con=new Sqlconnection("Data Source=PC85AAIEw\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True")){
cmd.Connection = con
con.Open()
Dim theQuery As String = "SELECT * FROM Profile WHERE RollNo=#RollNo AND Name=#Name"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#RollNo", TextBox1.Text)
cmd1.Parameters.AddWithValue("#Name", TextBox2.Text)
Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User already registered! Please try again.", "Error", MessageBoxButtons.OK)
Else
cmd.CommandText = "INSERT INTO Profile VALUES ('" & rollno & "' , '" & name & "' , '" & gender & "' , '" & address & "' , '" & phoneno & "' , '" & datereg & "' , '" & faculty & "' , '" & course & "' , '" & semester & "')"
MessageBox.Show("Profile has been successfully registered!", "Thank you", MessageBoxButtons.OK)
i = cmd.ExecuteNonQuery()
End If
End Using
con.Close()}
Related
I want to sort the data in the database with the date as the main condition with 2 date time picker 1 as the starting date and the other as the limit with this code by using between but I do not know the correct query form...my from looks like this the first DTP name is DTPDari and second DTPSampai
Call KONEKSI()
CMD = New OleDbCommand("SELECT * FROM Pembayaran where tanggal_pembayaran BEETWEEN '" & DTPDari.Value & "'AND tanggal_pembayaran = '" & DTPSampai.Value & "'", CONN)
DR = CMD.ExecuteReader
DR.Read()`
From the little what I understand from your question you can use any of the below
(syntax not tested)
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran BETWEEN '" & DTPDari.Value & "' AND '" & DTPSampai.Value & "')
or
SELECT * FROM Pembayaran where tanggal_pembayaran
WHERE (tanggal_pembayaran > '" & DTPDari.Value & "') and (tanggal_pembayaran < '" & DTPSampai.Value & "')
Adding Function sample asper your request
Sub GetDetails()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString.ToString()
Dim connection As New SqlConnection(connectionString)
Dim queryString2 = "SELECT *
FROM dbo.Customers
WHERE (CreationDate BETWEEN #param1 AND #param2)"
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandText = queryString2
cmd.Connection = connection
cmd.Parameters.AddWithValue("#Param1", from_DateTimePicker.Value.Date)
cmd.Parameters.AddWithValue("#param2", to_DateTimePicker.Value.Date)
connection.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
'here fill on datatable Or anything you want
End While
connection.Close()
End Sub
I am developing a Windows Form application using vb.net in VS10 with user management. I am using following code when a user tries to login:
Try
Dim sel As String
sel = "SELECT uid, name, loginid, password, type FROM user_master WHERE loginid = '" & UsernameTextBox.Text & "' AND password = '" & PasswordTextBox.Text & "'"
Dim cnn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\RSMS_DB.mdf;Integrated Security=True;User Instance=True")
Dim da As New SqlDataAdapter(sel, cnn)
Dim ds As New DataSet()
da.Fill(ds)
If ds.Tables(0).Rows.Count = 0 Then
MsgBox("Wrong Username and Password Combination!", MsgBoxStyle.Critical, "Login Failed")
Else
current_uid = ds.Tables(0).Rows(0)(0)
current_name = ds.Tables(0).Rows(0)(1)
current_loginid = ds.Tables(0).Rows(0)(2)
current_password = ds.Tables(0).Rows(0)(3)
current_type = ds.Tables(0).Rows(0)(4)
MsgBox("Welcome '" & ds.Tables(0).Rows(0)(1) & "'!", MsgBoxStyle.OkOnly, "Login Successful")
Dim upd = "UPDATE user_master SET lastlogin = '" & System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") & "' WHERE uid = " & current_uid & ""
Dim cmd As New SqlCommand(upd, cnn)
cnn.Open()
cmd.ExecuteNonQuery()
If checkboxLoginState.Checked = True Then
cmd.CommandText = "INSERT INTO login_state VALUES('" & current_uid & "', '" & current_name & "', '" & current_loginid & "', '" & current_password & "', '" & current_type & "')"
cmd.ExecuteNonQuery()
End If
cnn.Close()
load_user_permissions(current_uid) 'DISABLING OPTIONS ACCORDING TO USER RIGHTS
Me.Close()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Database Error")
End Try
All I want to ask is if it is the right method? Is the SELECT Query case sensitive by default?
The SQL Keywords are case-insensitive (SELECT, FROM, WHERE, etc), but are often written in all caps. However in some setups table and column names are case-sensitive. Usually case-sensitive table and column names are the default. If you want to change it then you can change it in a function of the database's collation settings.
Source - And this could also be helpful for you.
If security is important to you then you should hash the passwords - do not save passwords as plain text! You should check out the library libsodium
I have an SQL table with 4 columns. The fourth column is FullName. I want this column to autofill itself from the results of 2nd and 3rd Column. ie.Firstname and Middlename.
I have tried this code
cn.Open()
Dim query As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', CONCATE(Textbox2.text, ',', Textbox3.Text))"
cmd = New SqlCommand(query, cn)
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
The section CONCATINATE will be like the following:
"CONCATE('" & Textbox2.text &"',',','" & Textbox3.Text & "'))"
But i wont tell you to use like this, since it may a worst suggestion. I prefer you to use parameters as well to avoid injection and specifying the types.
Example:
Dim query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES (" & _
"#adm,#fName,#mName,CONCATE(#fNameC,',',#mNameC))"
Dim cmd As New SqlCommand(query, cn)
cmd.Parameters.Add("#adm", SqlDbType.VarChar).Value = TextBox1.Text
cmd.Parameters.Add("#fName", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#mName", SqlDbType.VarChar).Value = TextBox3.Text
cmd.Parameters.Add("#fNameC", SqlDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("#mNameC", SqlDbType.VarChar).Value = TextBox3.Text
'Execute the query here
Before query first store two textbox value in one variable
cn.Open()
Dim query As String
Dim fullname As String
fullname = TextBox1.text + "" + TextBox2.text
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', '" & fullname & '")"
cmd = New SqlCommand(query, cn)
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
You can concatenate with String.Concat, and I advice you to use the Parameter to avoid sql injections, like this :
cn.Open()
Dim query As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES (#Adm,#FirstName,#MiddleName,#FullName)"
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add(New SqlParameter("#Adm", TextBox1.Text))
cmd.Parameters.Add(New SqlParameter("#FirstName", TextBox2.Text))
cmd.Parameters.Add(New SqlParameter("#MiddleName", TextBox3.Text))
cmd.Parameters.Add(New SqlParameter("#FullName", String.Concat(TextBox2.Text, ",", TextBox3.Text)))
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
Save the Firstname and Middlename values into variables and concat() them together before sending to the query.
cn.Open()
Dim query As String
Dim firstname As String
Dim middlename As String
Dim fullname As String
query = "Insert into Details(Adm,FirstName,MiddleName,FullName) VALUES (#Adm,#FirstName,#MiddleName,#FullName)"
firstname = TextBox2.Text
middlename = TextBox3.Text
fullname = String.Concat(firstname, ",", middlename)
cmd = New SqlCommand(query, cn)
cmd.Parameters.Add(New SqlParameter("#Adm", TextBox1.Text))
cmd.Parameters.Add(New SqlParameter("#FirstName", firstname))
cmd.Parameters.Add(New SqlParameter("#MiddleName",middlename))
cmd.Parameters.Add(New SqlParameter("#FullName", fullname))
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
Note that the query builder has been reformatted to remove vulnerability to SQL injection.
Use following line instead of your.
query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', '" & Textbox2.Text & " " & Textbox3.Text & "')"
i have this code that will save only the top row of the datagridview,
can someone help me to modify this code so that it will save all the row in datagridview. im using vb 2010 and my database is ms access. thankyou in advance.
Try
Dim cnn As New OleDbConnection(conString)
query = "Insert into tblreportlog(EmpID,empname,department,empdate,timeinaM,timeoutam,lateam,timeinpm,timeoutpm,latepm,thw) values ('" & dgvReport.Item(0, dgvReport.CurrentRow.Index).Value & "', '" & dgvReport.Item(1, dgvReport.CurrentRow.Index).Value & "', '" & dgvReport.Item(2, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(3, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(4, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(5, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(6, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(7, dgvReport.CurrentRow.Index).Value & "', '" & dgvReport.Item(8, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(9, dgvReport.CurrentRow.Index).Value & "','" & dgvReport.Item(10, dgvReport.CurrentRow.Index).Value & "')"
cmd = New OleDbCommand(query, cnn)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
Catch ex As Exception
MsgBox("ERROR: " & ErrorToString(), MsgBoxStyle.Critical)
End Try
Working from what is shown and best practices injected, you should be working from a data source such as a DataTable e.g. if when presented the DataGridView to the user there are no rows then create a new DataTable, set the DataTable as the DataSource of the DataGridView then when you are ready to save these rows in the DataGridView cast the DataSource of the DataGridView to a DataTable and use logic similar to the following
Dim dt As DataTable = CType(DataGridView1.DataSource, DataTable)
If dt.Rows.Count > 0 Then
Using cn As New OleDb.OleDbConnection With {.ConnectionString = "Your connection string"}
' part field list done here
Using cmd As New OleDb.OleDbCommand With
{
.Connection = cn,
.CommandText = "Insert into tblreportlog(EmpID,empname,department) values (#EmpID,#empname,#department)"
}
' TODO - field names, field types
cmd.Parameters.AddRange(
{
{New OleDb.OleDbParameter With {.ParameterName = "#EmpID", .DbType = DbType.Int32}},
{New OleDb.OleDbParameter With {.ParameterName = "#empname", .DbType = DbType.Int32}},
{New OleDb.OleDbParameter With {.ParameterName = "#department", .DbType = DbType.String}}
}
)
Dim Affected As Integer = 0
cn.Open()
Try
For Each row As DataRow In dt.Rows
' this should not be a auto-incrementing key
cmd.Parameters("#EmpID").Value = row.Field(Of Integer)("FieldName goes here")
cmd.Parameters("#empname").Value = row.Field(Of Integer)("FieldName goes here")
cmd.Parameters("#department").Value = row.Field(Of String)("FieldName goes here")
Affected = cmd.ExecuteNonQuery
If Affected <> 1 Then
Console.WriteLine("Error message, insert failed")
End If
Next
Catch ex As Exception
'
' handle exception
'
' for now
MessageBox.Show("Failed with: " & ex.Message)
' decide to continue or not
End Try
End Using
End Using
End If
On the other hand, if there are new rows with current rows we cast the data source as above then check for new rows along with validation as needed.
For Each row As DataRow In dt.Rows
If row.RowState = DataRowState.Added Then
If Not String.IsNullOrWhiteSpace(row.Field(Of String)("CompanyName")) Then
Other options, utilize a DataAdapter or setup data via data wizards in the ide where a BindingNavigator is setup with a save button.
If it's important to get the new primary key back the method for all methods can do this too.
The following code sample is from this MSDN code sample that shows how to get a new key back using OleDb connection and command.
Public Function AddNewRow(ByVal CompanyName As String, ByVal ContactName As String, ByVal ContactTitle As String, ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Try
Using cn As New OleDb.OleDbConnection(Builder.ConnectionString)
Using cmd As New OleDb.OleDbCommand("", cn)
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName,ContactTitle) Values (#CompanyName,#ContactName,#ContactTitle)"
cmd.Parameters.AddWithValue("#CompanyName", CompanyName.Trim)
cmd.Parameters.AddWithValue("#ContactName", ContactName.Trim)
cmd.Parameters.AddWithValue("#ContactTitle", ContactTitle.Trim)
cn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
I've found some tutorials on this already, but they aren't exactly what I'm looking for, I can use the following for username fields and password fields
Private Sub UsernameTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles UsernameTextBox.KeyPress
If Char.IsDigit(e.KeyChar) OrElse Char.IsControl(e.KeyChar) OrElse Char.IsLetter(e.KeyChar) Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
But for an email field how would I go about protecting against SQL injection for that textbox, as some email accounts have periods or dashes in them?
Update:
Below is an example of an insert statement I use.
Dim con As SqlConnection
con = New SqlConnection()
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=" & Server & ";Initial Catalog=" & Database & ";User ID=" & User & ";Password=" & Password & ";"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO TB_User(STRUserID, password, Email) VALUES('" & UsernameTextBox.Text & "', '" & MD5Hash(PasswordTextBox.Text) & "', '" & EmailTextBox.Text & "')"
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
So I need to run this with parametrized queries rather than how I'm doing it now?
Instead of filtering out "invalid" data from user input, consider using parametrized queries and not putting user input directly into your queries; that's very bad form.
To run your current query using parameters, it's pretty easy:
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Try
con.ConnectionString = "Data Source=" & Server & ";Initial Catalog=" & Database & ";User ID=" & User & ";Password=" & Password & ";"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO TB_User(STRUserID, password, Email) VALUES(#username, #password, #email)"
cmd.Parameters.Add("#username", SqlDbType.VarChar, 50).Value = UsernameTextBox.Text
cmd.Parameters.Add("#password", SqlDbType.Char, 32).Value = MD5Hash(PasswordTextBox.Text)
cmd.Parameters.Add("#email", SqlDbType.VarChar, 50).Value = EmailTextBox.Text
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
All you have to do is use cmd.Parameters.Add with a parameter name and the right database type (the ones I guessed probably don't match up, so you'll want to change them), then set the value to the value you want used in the query. Parameter names start with an #.
It doesn't depend on the textbox. Don't compose a sql sentence joining strings like this:
"SELECT * FROM User WHERE UserName=" + tbName.Text + ...
Use stored procedures or parameterized queries and you'll be safe from SQL injection.
When you use parameters, the textbox content is used as a value, so it doesn't matter what it contains.
Use a parametrized query like this:
Using conn = New SqlConnection("some connection string")
Using cmd = New SqlCommand("SELECT Password FROM tblUser WHERE UserName = #Name", conn)
cmd.Parameters.Add(New SqlParameter("Name", UsernameTextBox.Text))
conn.Open()
Dim password As String = DirectCast(cmd.ExecuteScalar(), String)
Console.WriteLine(password)
End Using
End Using
This is injection safe!