VB.net to SQL Server INSERT checkbox results - sql-server

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

Related

How to fix ADODB connection simple login code WPF

I have been dying in solving the issue in my code my goal is to simply look for the account relative to the user's input. I have been encountering closed states of my record set and or having no response at all from my program i need some clarifications on my code and I also would like to know the best practices in implementing a ADODB connection as SQL query
Dim WithEvents ErrorMessageTimer As New DispatcherTimer
Private Sub BTNLogin_Click(sender As Object, e As RoutedEventArgs) Handles BTNLogin.Click
If (Trim(FLDUsername.Text) = "") Then
LBLErrorMessage.Text = "Username is Empty"
LBLErrorMessage.Visibility = Visibility.Visible
ErrorMessageTimer.Interval = TimeSpan.FromSeconds(2.7)
ErrorMessageTimer.Start()
Else
Dim dbCon As New ADODB.Connection
Dim dbRecSet As New ADODB.Recordset
dbCon.Open("PROVIDER=Microsoft.jet.oledb.4.0;Data Source=inventory.mdb")
dbRecSet.Open("SELECT * FROM [User] WHERE Username='" & FLDUsername.Text & Chr(39), dbCon, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockOptimistic)
Try
If (dbRecSet.Fields("Username").Value = FLDUsername.Text) And (dbRecSet.Fields("Password").Value = FLDPassword.Password) Then
Dim mainMenu As New MainMenuWindow
Me.Hide()
mainMenu.Show()
Else
ErrorMessageTimer.Start()
LBLErrorMessage.Text = "! Invalid Credentials"
End If
Catch ex As Exception
ErrorMessageTimer.Start()
LBLErrorMessage.Text = "! Account not Found"
End Try
dbCon.Close()
dbRecSet.Close()
End If
End Sub
I will repeat my comments here so you don't miss them.
Dump the ancient ADODB and switch to ADO.net. No Com interop.
Do not concatenate strings with user input to build Sql commands. You are risking Sql injection.
NEVER store passwords as plain text.
Using Parameters avoids the risk of Sql injections because the values will not be considered to be executable code. For OleDb (Access) the names of the parameters do not matter. It is the order that they are added to the ParametersCollection must match the order that they appear in the Sql command. Not only will parameters protect your database, they make it easier to write the Sql. No single quotes, double quotes, ampersands.
The Using...End Using blocks will ensure that your database objects are closed and disposed even if there is an error.
I don't think your Data Source = inventory.mdb will be sufficient for the file to be found. A complete path would be better.
I will leave it to you to research how to salt and hash passwords for storage and then retrieve and compare to user input.
Private Sub BTNLogin_Click(sender As Object, e As RoutedEventArgs) Handles BTNLogin.Click
If FLDUsername.Text = "" OrElse FLDPassword.Text = "" Then
'Make this visible at Design time
LBLErrorMessage.Text = "Please fill in both fields."
'I have no idea what you are trying to do with your timer.
Return
End If
Dim RetVal As Integer
Try
Using dbCon As New OleDbConnection("PROVIDER=Microsoft.jet.oledb.4.0;Data Source=inventory.mdb")
Using cmd As New OleDbCommand("SELECT Count(*) FROM [User] WHERE [Username] = #UserName And [Password] = #Password;", dbCon)
cmd.Parameters.Add("#UserName", OleDbType.VarChar, 50).Value = FLDUsername.Text
cmd.Parameters.Add("#Password", OleDbType.VarChar, 50).Value = FLDPassword.Text
dbCon.Open()
RetVal = CInt(cmd.ExecuteScalar())
End Using
End Using
Catch ex As Exception
'An error here is probably due to invalid connection of network error
'Show the error message not "! Account not Found"
MessageBox.Show(ex.Message)
Return
End Try
'Now your connection is closed and your objects disposed.
'Only after the last End Using do we evaluate the results of our query
'and take action.
If RetVal = 1 Then
Dim mainMenu As New MainMenuWindow
Me.Hide()
mainMenu.Show()
Else
LBLErrorMessage.Text = "! Invalid Credentials"
End If
End Sub

StoredProcedure executes in SSMS, not in VB.NET application (no SqlException thrown)

I have a SQL StoredProcedure that performs two INSERT INTO operations in SSMS as expected.
When executing this SP in my VB.NET application, it is executing (no SqlException thrown in Try block) but not executing the INSERT INTO commands.
This application uses numerous SP's that all work without problems.
Code is as follows:
Using (ParentMDI.dbCon)
Dim sqlcmd As New SqlCommand("hyd_top_level_isr")
With sqlcmd
.CommandType = CommandType.StoredProcedure
.Parameters.AddWithValue("#part_num", part_num)
.Parameters.AddWithValue("#issue", issue)
End With
Try
sql.ExecuteNonQuery()
Catch ex As SqlException
If DialogResult.Yes = MessageBox.Show("Error inserting top-level ISR." & vbCrLf & vbCrLf & "Send Error Report?", "Workflow Error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) Then
ParentMDI.emailerrorstring = "Stored Procedure: hyd_top_level_isr"
ParentMDI.emailerrormessage = ex.Message
ParentMDI.ErrorEmail()
End If
End Try
End Using
For clarification;
I have inserted breakpoints before ExecuteNonQuery(). The sub does execute the ExecuteNonQuery() and the parameters being passed are populated with the correct values.
I have also inserted a RETURN in the SP to return the SCOPE_IDENTITY(). This returns an empty string (not NULL, as I was expecting).
If any of you need more information, please let me know.
I will be massively appreciative of anyone who can educate me on where I'm going wrong!
(This is my first time ever asking for help, please be kind!) :)
EDIT:
Sorry guys. I seem to have lead you on incorrectly. The code pasted above is me trying all sorts of different attempts at trying to solve this. What I'll post now is what I should have posted in the first place. With the same outcome. Sorry for the confusion, and thanks for your attempts so far...
Dim sqlcmd As New SqlCommand("hyd_top_level_isr", ParentMDI.dbCon)
With sqlcmd
.CommandType = CommandType.StoredProcedure
.Parameters.AddWithValue("#part_num", part_num)
.Parameters.AddWithValue("#issue", issue)
End With
Try
sqlcmd.ExecuteNonQuery()
Catch ex As SqlException
If DialogResult.Yes = MessageBox.Show("Error inserting top-level ISR." & vbCrLf & vbCrLf & "Send Error Report?", "Workflow Error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) Then
ParentMDI.emailerrorstring = "Stored Procedure: hyd_top_level_isr"
ParentMDI.emailerrormessage = ex.Message
ParentMDI.ErrorEmail()
End If
End Try
In addition to #Zohar Peled's comment I think you should set sqlCmd's connection and use sqlCmd.ExecuteNonQuery. Below you should also use local sqlConnection.
Using sqlcmd As New SqlCommand("hyd_top_level_isr", ParentMDI.dbCon)
With sqlcmd
.CommandType = CommandType.StoredProcedure
.Parameters.AddWithValue("#part_num", part_num)
.Parameters.AddWithValue("#issue", issue)
End With
Try
sqlCmd.ExecuteNonQuery()
Catch ex As SqlException
'' Handle exception here
End Try
End Using
Firstly I think that in SQLCommand you should pass the SQL connection like:
Dim sqlcmd As New SqlCommand("hyd_top_level_isr", ParentMDI.dbCon)
Secondly, you are not run sqlcmd but sql.executenonquery.
Third, executenonquery is an integer. If you dim a variable:
Dim result = sqlcmd.ExecuteNonQuery()
What do you get?

Error converting data type nvarchar to date

I am trying to execute a stored procedure that will take the start and end time from my DateTimePicker and check to see if a vehicle is available and return a dataset with those that are. The code does work when I run it in SQL Managment Studio, so I am trying to execute with VBA in Visual studio.
I will plan to post later on help with displaying the dataset as I am not sure how to do this in code and have had a hard time finding good examples but for now I am trying to get past this error message. I have gone back and changed the format to a custom format so it matches the date format in my SQL database. The custom format I am using on both datetimepickers is yyyy-MM-dd. I have tried several of the suggestions on the various websites but no luck so far getting past this message. Below is the code from my stored procedure as well as the visual basic code.
CREATE PROC spVehicleAvailable
#RequestedStartDate Date,--DateTime selectedDate = dateTimePicker1.Value.Date
#RequestedEndDate Date--DateTime selectedDate = dateTimePicker2.Value.Date
AS
BEGIN
Select Vehicle.*
FROM Vehicle
Where Vehicle.VehicleID NOT IN (
SELECT VehicleID FROM LoanRequest
WHERE #RequestedEndDate >= LoanRequest.StartDate
AND #RequestedStartDate <= LoanRequest.EndDate)
AND Available = 1 AND Scrap=0
END;
Private Sub btnAvailable_Click(sender As Object, e As EventArgs) Handles btnAvailable.Click
Try
Dim sqlConnection1 As New SqlConnection("Data Source=GALE-PC1\SQLEXPRESS2012;Initial Catalog=VehicleCheckout;Integrated Security=True")
Dim cmd As New SqlCommand
cmd.CommandText = "spVehicleAvailable"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
cmd.Parameters.AddWithValue("#RequestedStartDate", Date.ParseExact(dtpStartDate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture))
cmd.Parameters.AddWithValue("#RequestedEndDate", Date.ParseExact(dtpEndDate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture))
'new code to try adding info into datagridview
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet("Vehicles") ' Not sure of this code
da.SelectCommand.Parameters(0).Value = "Not-Sure" 'Not sure of this code
da.Fill(ds)
If Not ds Is Nothing Then
MessageBox.Show("This Vehicle" & ds.Tables(0).Rows(0)("SomethngElse").ToString) 'Not sure of this code
End If
'end new code
sqlConnection1.Open()
cmd.ExecuteNonQuery()
sqlConnection1.Close()
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
When you execute this : Date.ParseExact(dtpStartDate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture) in a imediate window, what's the result?

extract information from MS SQL database

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

How to update MS Access Database (vb.net)

I am created a journal program for an internship project and I am using a MS-Access Database. I am programming in VB.net. Now, I am trying to make it so that they can "Update" their journals, meaning that they click on their calendar date and it brings them to that journal if they have one for that date. If they have one for that date then it shows the title and journal text entry for that date. I want to make it so that any changes they have made to the journal (editing the textbox fields) are also changed in the database when they click the update button. Here's what i have so far
Private Sub COE_JournalBtn_Click(sender As System.Object, e As System.EventArgs) Handles COE_JournalBtn.Click
If DateTimePicker1.Value <> Nothing Then
If TitleTxt.Text <> "" Then
If JournalTextRtxt.Text <> "" Then
myConnection.Open()
Dim DatePicked As String = DateTimePicker1.Value
Dim cmd As OleDbCommand
Dim str As String
Try
MyJournalTitle = TitleTxt.Text
MyJournalText = JournalTextRtxt.Text
str = "UPDATE Journals SET JournalTitle='" & MyJournalTitle & "', JournalText='" & MyJournalText & "' WHERE JournalDate=" & DatePicked
cmd = New OleDbCommand(str, myConnection)
cmd.ExecuteNonQuery()
myConnection.Close()
Catch ex As Exception
MessageBox.Show("There was an error processing your request. Please try again." & vbCrLf & vbCrLf & _
"Original Error:" & vbCrLf & vbCrLf & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
myConnection.Close()
End Try
myConnection.Close()
End If
End If
End If
End Sub
Now my update string by itself is
"UPDATE Journals SET JournalTitle='" & MyJournalTitle & "', JournalText='" & MyJournalText & "' WHERE JournalDate=" & DatePicked
Now, what happens, is absolutely nothing. No errorboxes come up. No messageboxes appear. The program doesn't freeze. And the database remains unchanged. What am I doing wrong? Is there an error in my code or something missing? Please help me because I really want to figure this out and i've been looking everywhere for a solution in VB.net and cannot find one that applies to me being that I am using MS-Access and NOT SQL.
Thanks in advance,
Richard Paulicelli
Use a parametrized query to avoid Sql Injection Attacks and quoting problems
str = "Journals SET JournalTitle=?, JournalText=? WHERE JournalDate=?"
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#jounalTitle", MyJournalTitle )
cmd.Parameters.AddWithValue("#journalText", MyJournalText)
cmd.Parameters.AddWithValue("#journalDate", DatePicked)
cmd.ExecuteNonQuery()
Using parameters will free your code from that continue quoting that expose your code to an high chance of typing errors. And you don't have any problem with Sql Injection
You may have a problem with this part of your UPDATE statement:
"' WHERE JournalDate=" & DatePicked
If the Journals field, JournalDate, is Date/Time data type, surround the date string value with Access date delimiter characters (#).
"' WHERE JournalDate=#" & DatePicked & "#"
You can also convert your date string to yyyy-mm-dd format to avoid misinterpreting the date literal based on local.
I agree with the suggestions to use a parameter query for this instead. I'm just trying to help you understand why the original attempt may have failed.

Resources