VB to SQL server - sql-server

I'm trying to insert new data into an SQL server from what user had input in a textbox.
My code is not functioning, please help me.
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Data Source=LANDSLIDE\SQLSERVER2005;Initial Catalog=PayrollSQL;User ID=sa;Password=lismyadmin"
cmd.Connection = con
con.Open()
cmd.CommandText = "INSERT INTO dbo.Member ([Name], [Code], [NRIC]) VALUES(" & TextBox1.Text & "," & TextBox2.Text & "," & TextBox3.Text & ")"
cmd.ExecuteNonQuery()
con.Close()

You ought to use parameterised queries. Something like:
cmd.CommandText = "INSERT INTO dbo.Member ([Name], [Code], [NRIC]) VALUES(#Name,#Code,#NRIC)"
cmd.Parameters.AddWithValue("#Name",TextBox1.Text)
cmd.Parameters.AddWithValue("#Code",TextBox2.Text)
cmd.Parameters.AddWithValue("#NRIC",TextBox3.Text)
At the moment, you're ending up with your strings appearing literally in your SQL statement - and whatever values you're retrieving from TextBox1-3 aren't valid pieces of SQL (hopefully - if they are actually valid SQL, you're performing SQL injection)
(By the way, you're allowed to rename controls - you ought to rename those TextBoxes so that you don't have to remember that, say, TextBox2 is the one for code)

May be it will work or else provide error message:
cmd.CommandText = "INSERT INTO dbo.Member ([Name], [Code], [NRIC]) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "')"

Related

Inserted data automatically deleted from database after application is terminated

I am trying to insert data into a table and then display that data in a DataGridView.
When I insert the data at runtime, the entered data displays in a DataGridView however after termination of the application, nothing is stored in my "mdf" file.
I am using piping method to store my connection string and setting the property "copy to output" of my mdf file to "copy always".
Does anybody know why my database is not retaining the data after terminating the application?
Code:
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("mycs").ConnectionString)
Dim cmd As New SqlCommand
cmd.Connection = con
con.Open()
cmd.CommandText = "insert into tbl_party_data (pname, paddress, ppan, pmobile, pemail) values ('" & txt1.Text & "','" & txt2.Text & "','" & txt3.Text & "','" & txt4.Text & "','" & txt5.Text & "')"
cmd.ExecuteNonQuery()
Dim adp As SqlDataAdapter = New SqlDataAdapter _
("select * from tbl_party_data", con)
Dim ds As DataSet = New DataSet()
adp.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)

I can't seem to insert data to my database

I am having issues with my code when I try to insert data into my database, the section where it checks for matching username keeps popping up the error to select another username. I don't know what I am doing wrong, any help will be appreciated.
This is my code:
'Connecting to SQL Database and executing Query
Dim Strconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\phermacy.mdf;Integrated Security=True;User Instance=True"
Dim Strcmd As String = "INSERT INTO tblstaff_info(id,fname,lname,sex,nationality,status,dob,age,nationality,state,address,phone,email,dateemp,username,password) VALUES ('" & txtregid.Text & "','" & txtfname.Text & "','" & txtlname.Text & "','" & cmbstaffsex.Text & "','" & cmbstatus.Text & "','" & dtpickerdob.Text & "','" & txtage.Text & "','" & txtnationality.Text & "','" & txtstateofo.Text & "','" & rtbaddress.Text & "','" & txtphone.Text & "','" & txtemail.Text & "','" & dtpdateemp.Text & "','" & txtusername.Text & "','" & txtpassword.Text & "');"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim sqlcmd As SqlCommand
sqlconn = New SqlConnection(Strconn)
Try
sqlconn.Open()
Catch ex As Exception
MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error")
End
End Try
sqlcmd = New SqlCommand(Strcmd, sqlconn)
da.SelectCommand = sqlcmd
sqlcmd.Dispose()
sqlconn.Close()
'Exception Handling-----------------------
Dim exc As Exception = Nothing
Try
da.Fill(ds)
Catch ex As Exception
exc = ex
Finally
If Not (exc) Is Nothing Then
MsgBox("User Name Already Exist. Please select a different User Name!", vbExclamation, "Already Exist")
txtusername.Focus()
Else
MsgBox("Save info Successful.", vbInformation, "Successful")
'Me.Close()
'loginform.Show()
End If
End Try
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the connection's .Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. Pharmacy - check your spelling!)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=Pharmacy;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.

VBA sql query based off combobox

I've been searching hard the past few days and have come across numerous examples that outline what I'm trying to do. However, I can't seem to get this working. I have a combobox that populates data (a company name) from a table when the form initializes. I then want to take the value chosen in the combo box and run another query to cross reference an id number in that same table.
Private Sub CommandButton1_Click()
Dim myCn As MyServer
Set myCn = New MyServer
Dim rs As ADODB.recordset
Set rs = New ADODB.recordset
Dim sqlStr As String
Dim CompField As String
'CompField = ComboBox1.Value
sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = '" & ComboBox1.Text & "'"
'sqlStr = "Select DISTINCT [company] FROM client;"
' sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Value & ";"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Text & ";"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = 'Company XYZ';"
'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE company = " & CompField & ""
rs.Open sqlStr, myCn.GetConnection, adLockOptimistic, adCmdText
MsgBox sqlStr
'MsgBox ComboBox1.Value
'MsgBox rs(0)
rs.Close
myCn.Shutdown
Set rs = Nothing
Set myCn = Nothing
End Sub
Currently with the combobox value encased in single quotes i get the entire sql string returned. If I remove the single quotes I get a syntax error referencing part of the combobox value. All other efforts have resulted in run-time errors that have led me nowhere.
I know my query works because I've tested it in SQL Studio and if I hard code a text value in this code I also get the Account ID I'm looking for. Not sure what I'm missing here.
Well I figured it out. I was expecting to be able to MsgBox the variable assigned to the SQL query and see my results. But it doesn't work that way. I had to use ADO GetString method for that and assign another variable. Oh and you were right about escaping, I had to add delimters to properly handle the ComboBox value in the query which ultimately looked like this
sqlStr = "SELECT DISTINCT [acct_no] FROM client WHERE [company] = " & Chr(39) & Me.ComboBox1.Value & Chr(39)
Thanks for your help on this

How to save the columns which i added in my datagridview using access database VB.net 2010

I'm using this code to add a new column:
DataGridView1.Columns.Add("Test", "TesT")
but after saving and closing the project then I open it again the columns were deleted.
The question is how to save the columns to the access database.
If your just going to save the values, than you'd have to call them back up in order to fill the grid.
Sample code to insert into an access db.
Dim Cmd as New OLEDb.OleDbCommand
Dim oleConn as New OleDb.OleDbConnection
Dim strDataBase as String
strDataBase = "C:\Test.mdb"
'2007 connection string will work for 2003-2007 databases - change to 14.0 for 2010 etc
oleConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strDataBase & ";Jet OLEDB"
Cmd.Connection = oleConn
oleConn.Open()
Cmd.CommandText = "Insert into mytable ( Field1, Field2 ) values ( '" & "some Value" & "', '" & "some value" & "' )"
Cmd.ExcuteNonQuery
oleConn.Close()

Why is sql server giving a conversion error when submitting date.today to a datetime column?

I am getting a conversion error every time I try to submit a date value to sql server. The column in sql server is a datetime and in vb I'm using Date.today to pass to my parameterized query. I keep getting a sql exception
Conversion failed when converting datetime from character string.
Here's the code
Public Sub ResetOrder(ByVal connectionString As String)
Dim strSQL As String
Dim cn As New SqlConnection(connectionString)
cn.Open()
strSQL = "DELETE Tasks WHERE ProjID = #ProjectID"
Dim cmd As New SqlCommand(strSQL, cn)
cmd.Parameters.AddWithValue("ProjectID", 5)
cmd.ExecuteNonQuery()
strSQL = "INSERT INTO Tasks (ProjID, DueDate, TaskName) VALUES " & _
" (#ProjID, #TaskName, #DueDate)"
Dim cmd2 As New SqlCommand(strSQL, cn)
cmd2.CommandText = strSQL
cmd2.Parameters.AddWithValue("ProjID", 5)
cmd2.Parameters.AddWithValue("DueDate", Date.Today)
cmd2.Parameters.AddWithValue("TaskName", "bob")
cmd2.ExecuteNonQuery()
cn.Close()
DataGridView1.DataSource = ds.Projects
DataGridView2.DataSource = ds.Tasks
End Sub
Any thoughts would be greatly appreciated.
Try
DateTime.Now()
Or
DateTime.Today;
Instead of
Date.Today
Could be an issue with different regional settings between your application and SQL server.
Although it doesn't resolve the underlying issue, a straight-forward way to avoid this is by explicitly formatting the date you pass to SQL
cmd2.Parameters.AddWithValue("DueDate", DateTime.Today.ToString("yyyyMMdd"));
EDIT:
I read your code more carefully: you've got your parameters and values in different orders. Try:
strSQL = "INSERT INTO Tasks (ProjID, DueDate, TaskName) VALUES " & _
" (#ProjID, #DueDate, #TaskName)"
Parameters were in the wrong order. Doh!
#TaskName and #DueDate were swapped. I believe all of the above suggestion are correct.
strSQL = "INSERT INTO Tasks (ProjID, DueDate, TaskName) VALUES " & _ " (#ProjID, #TaskName, #DueDate)"

Resources