My database has a table called "SerialKey" 3 columns id which is PK Email & Serial.
I have a windows form in VB.NET, the form has 1 label, 1 TextBox, 1 Button,
The text in the label displays an email address, this email address will vary. When I click the button on the form I want the database to be searched for the email address and find the serial in the database. I have shown the code below but it gives me an error saying
"Object reference not set to an instance of an object" it highlights the line below.
Dim reader As SqlDataReader = command.ExecuteReader()
Can someone help me out here because I'm truly stuck and truly new :)
Any help appreciated.
con = New SqlConnection("Data Source= My connection string here; Password='my password here'; ")
cmd.Connection = con
cmd.CommandText = "SELECT Serial FROM SerialKey Where Serial= ?"
cmd.Parameters.AddWithValue("?", LblName.Text)
con.Open()
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
'Do something
If lrd.HasRows Then
lrd.Read()
UsersKey.Text = lrd.GetString(1)
TextBox2.Text = lrd.GetString(2)
End If
End While
Catch ex As Exception
MessageBox.Show("Error while retrieving records on table..." & ex.Message, "Load Records")
Finally
con.Close()
End Try
Related
I have developed an application which runs with multiple instance simultaneously. In the application it connects to a SQL Server and fetches some data, while working on that data, it updates the row as picked so that no other instance of the application picks up the same record for research. While updating the row for the fetched record, sometime it gets deadlock issue and not updating the record as already picked.
Dim MyConnection As SqlConnection
Try
MyConnection = New SqlConnection(connString)
MyConnection.Open()
Dim tableName As String = myTableName
Dim sqlQuery As String = "Select Top 1 * from " + tableName + " where "<some condition>
Dim MyCommand As SqlDataAdapter = New SqlDataAdapter(sqlQuery, MyConnection)
Dim DS as DataSet = New DataSet
MyCommand.Fill(DS, tableName)
If DS.Tables(0).Rows.Count >= 1 Then
sqlQuery = "UPDATE " + tableName + " SET Fld = #fld where Cond1= '" + DS.Tables(0).Rows(0).Item("Cond1").ToString + "'"
Dim cmd As New Data.SqlClient.SqlCommand(sqlQuery)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#fld", Data.SqlDbType.VarChar).Value = "Picked"
Try
cmd.Connection = MyConnection
cmd.ExecuteNonQuery() <---- Dead lock occurs here
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
Catch ex As Exception
MsgBox(ex.ToString)
Finally
MyConnection.Close()
End Try
While executing the update statement, deadlock occurs and it goes to catch block and then exits the sub without updating the required field in the table. I want it to try to update until the dead lock is removed.
Creating Stored Procedure is not possible as I do not have the admin rights to this DB.
How can I overcome the problem?
I'm writing a VB.net program that records data in SQL Server 2012. At this stage I'm trying to create a new row in the database. The primary key automatically creates a line N+1, and to create the line you enter a new serial number. This all worked the other day, except you could not then load the row into the form to edit the rest of the data because it was tripping up on the nulls.
Anyway, I decided as I created the new row I'll load a blank space " " into all text boxes, today's date into all date boxes and a 'false' return on all check boxes. I've also added code to check for nulls. Below is the code to insert a result into the checkboxes, but I get an error
Incorrect syntax near '='
My code:
Private Sub btnAddNewSerial_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click, btnAddNewSerial.Click
Try
con.ConnectionString = (frmAdmin.lblDBConnection.Text & frmAdmin.txtDBPW.Text & frmAdmin.lblDBConnection2.Text)
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO SLE1000DB (SK2SoakMainPCB) " & _
"VALUES (#SK2SoakMainPCB)”
cmd.Parameters.AddWithValue("#SK2SoakMainPCB", SqlDbType.Bit).Value = FrmSLE1000.chkSoakInteruptionsMainPCB.Checked
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
con.Close()
MsgBox("Data updated")
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
Me.Hide()
frmSelect.Show()
End Sub
So if anyone can see whats causing the syntax error or can tell me a neater way of causing the checkbox to return a false result (I know that at the moment if it did work it would return a true result, that's something I'm still thinking about) Or just an overall neater way to achieve my goal that would be much appreciated. All my knowlage of VB.net and SQL Server comes from a book so is therefore, unfortunately, pretty limited!
The code presented here is just a snippet, there's actually an awful lot more columns that I'm passing data to, but I believe that its the checkboxes that are causing the syntax error as there aren't any "=" anywhere else in this bit of code and using a step through its this section that it gets caught up on.
Anyway thanks for your help!
Private Sub btnAddNewSerial_Click(sender As System.Object, e As
System.EventArgs) Handles btnAdd.Click, btnAddNewSerial.Click
Try
con.ConnectionString = (frmAdmin.lblDBConnection.Text &
frmAdmin.txtDBPW.Text & frmAdmin.lblDBConnection2.Text)
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO SLE1000DB (SK2SoakMainPCB) VALUES (#SK2SoakMainPCB)"
cmd.Parameters.AddWithValue("#SK2SoakMainPCB",FrmSLE1000.chkSoakInteruptionsMainPCB.Checked)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
con.Close()
MsgBox("Data updated")
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
Me.Hide()
frmSelect.Show()
End Sub
the add parameter with value was incorrect. For more info : https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
hope this helps
I am trying to insert data into my Access database using vb for an application I am building. I have been BEATING my had off of an invisible wall trying to get the data to enter into the database. Below is the code, below that I will explain it more.
Private Sub btnSubmitExpense_Click(sender As Object, e As EventArgs) Handles btnSubmitExpense.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\PFADatabase.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "Insert into Expenses ([ExpenseTypeID], [DateOfExpense],[AmountOfExpense]) Values(?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("ExpenseTypeID", CType(cboCategoryOfExpense.Text, String)))
cmd.Parameters.Add(New OleDbParameter("DateOfExpense", CType(dateOfExpense.Text, String)))
cmd.Parameters.Add(New OleDbParameter("AmountOfExpense", CType(txtAmountOfExpense.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
'clear the form below
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
[ExpenseTypeID] is actually a lookup. The object is a combobox in vb that I have programmed above the code I posted here.
[DateOfExpense] is also a Date object in VB. I just dragged it over. I want that to be associated with everything in that table.
[AmountOfExpense] is again, tied into the db.
Basically a user enters the date using the tool, then chooses a category of their expense and then enters the amount. This is all one table but the expenseType is a Lookup actually within Access to another table so we could have the dropdown. Everything works well until I click the save button. Then whenever i do that I get the exception the type is mismatched. How do I fix that? I'm GUESSING it is the text string being wrong, but I've tried other things so I am thinking it is a bit more than that which is why I came here to you professionals to get input.
Thank you.
EDIT: The error is coming in at
cmd.ExecuteNonQuery()
and says "Data type mismatch in criteria expression. "
'START THE POPULATE THE COMBO BOXES
'Gets the database and makes the connection
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\PFADatabase.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
'Generates a query command
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [ExpenseType] FROM [ExpenseType]", myConnection)
myConnection.Open() 'Opens connection
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
cboCategoryOfExpense.Items.Add(dr.Item(0))
End While
myConnection.Close()
'END THE POPULATE OF COMBO BOXES
As you can see in the comments, it is saying how the combo boxes are populated.
EDIT: In the picture under Expenses is the main table. The circled value is the FK and it's leading to the PK of the ExpenseType. The data we are pulling the drop down from is the ExpenseType under ExpenseType. From what I understand, you guys are saying, and I agree, it's writing to the PK of ExpenseType and not the data. ALL I want it to do is keep the data categorized for a graph we will be using.
Convert your input to the appropriate datatype as required by your columns. If you don't specify the datatype of your parameters and pass always strings then you are easy target of this kind of errors
...
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Dim expID As Integer
if Not Int32.TryParse(cboCategoryOfExpense.Text, expID) Then
MessageBox.Show("Invalid integer")
return
End If
cmd.Parameters.Add("ExpenseTypeID", OleDbType.Integer).Value = expID
Dim dtExp as DateTime
if Not DateTime.TryParse(dateOfExpense.Text, dtExp) Then
MessageBox.Show("Invalid Date")
return
End If
cmd.Parameters.Add("DateOfExpense", OleDbType.Date).Value = dtExp
Dim amount As Decimal
if Not Decimal.TryParse(txtAmountOfExpense.Text, amount) Then
MessageBox.Show("Invalid Decimal")
return
End If
cmd.Parameters.Add("AmountOfExpense", OleDbType.Currency).Value = amount
....
Looking at your edit and comments, perhaps this is what you need
' Be sure to have a combobox with DropDownList style to avoid
' user entering an unexpected value then....
'Load the combobox from the table ExpenseType
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [ExpenseTypeID], " & _
"[ExpenseType] FROM [ExpenseType]", myConnection)
myConnection.Open() 'Opens connection
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim dt = new DataTable()
dt.Load(dr)
cboCategoryOfExpense.DataSource = dt
' The visible part of the combo contains value from ExpenseType field
cboCategoryOfExpense.DisplayMember = "ExpenseType"
' The hidden part refers to the ExpenseTypeID field
cboCategoryOfExpense.ValueMember = "ExpenseTypeID"
...
and now when converting the combobox value you coud write
Dim expID As Integer
' Sanity check in case the user want to insert but has not
' selected anything from the combobox
if cboCategoryOfExpense.SelectedValue Is Nothing Then
MessageBox.Show("Select an Expense")
return
End if
cmd.Parameters.Add("ExpenseTypeID", OleDbType.Integer).Value = Convert.ToInt32(cboCategoryOfExpense.SelectedValue)
....
I am not sure if it's me or there's something wrong with my code. Whenever I try to add a new account, it is being "saved" and shown in my datagridview, however, when I check under the data set or the table data, it's not being saved (or updated). I am using Visual Studio 2013 and I just checked my Microsoft SQL version - 2012. I did what I found here and in other sites, like uncheck the "Prevent saving changes that require table re-creation"; and I also changed the "Copy to output directory to Copy if newer", oh, and I also changed the |DataDirectory| to the path of the 2 mdf files.
Sorry if I'm asking a question that was asked before. And... here's my code (this one is for change password form):
If txtNewPass.Text = txtRetyped.Text Then
Dim strSql As String
Try
Dim objAdap As SqlDataAdapter
Dim objDt As New DataTable
strConn = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FHGES.mdf;Integrated Security=True"
objConn = New SqlConnection(strConn)
Dim s As String = "SELECT * FROM tblAccounts WHERE UName COLLATE Latin1_General_CS_AS='" & frmLogin.txtUname.Text & "'AND PWord COLLATE Latin1_General_CS_AS='" & frmLogin.txtPassword.Text & "';"
objComm = New SqlCommand(s, objConn)
objAdap = New SqlDataAdapter(objComm)
objAdap.Fill(objDt)
lblUName.Text = objDt.Rows(0)(4).ToString
strSql = "UPDATE tblAccounts SET PWord='" & txtRetyped.Text & "' WHERE UName='" & lblUName.Text & "'"
objComm = New SqlCommand(strSql, objConn)
objConn.Open()
objComm.ExecuteNonQuery()
objConn.Close()
MessageBox.Show("Saved new password, please re-login", "FHGES", MessageBoxButtons.OK)
frmLogin.Show()
frmLogin.txtPassword.Clear()
frmLogin.txtPassword.Focus()
Me.Hide()
Catch ex As Exception
MsgBox(ex.Message)
Finally
If objConn.State = ConnectionState.Open Then
objConn.Close()
End If
End Try
Else
MessageBox.Show("Password don't match!", "FHGES", MessageBoxButtons.OK)
txtNewPass.Clear()
txtRetyped.Clear()
txtNewPass.Focus()
End If
I am trying to display query results from SQL server in VB. I wrote following code, but not getting how to "Just display the results";
Public Function ConnectToSQL() As String
Dim con As New SqlConnection
Try
con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm"
Dim cmd As New SqlCommand("SELECT username FROM users WHERE username='user'", con)
con.Open()
Console.WriteLine("Connection Opened")
' Execute Query
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(String.Format("{0}, {1}", _
reader(0), reader(1)))
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection.
End Try
Return reader
End Function
Can any one guide? Thank you
I corrected a few things and now your function works fine for me:
Public Function ConnectToSQL() As String
Dim con As New SqlConnection
Dim reader As SqlDataReader
Try
con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm"
Dim cmd As New SqlCommand("SELECT username, WindowsLogin FROM users WHERE username='user'", con)
con.Open()
Console.WriteLine("Connection Opened")
' Execute Query '
reader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(String.Format("{0}, {1}", _
reader(0), reader(1)))
'NOTE: (^^) You are trying to read 2 columns here, but you only '
' SELECT-ed one (username) originally... '
' , Also, you can call the columns by name(string), not just by number '
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
'Return reader { note: reader is not valid after it is closed } '
Return "done"
End Function
Let me know if you have any questions.