I have a windows service (VB.NET) to copy data from a SQL table to another SQL table (in a different database & server). When I start the service it just give me this error:
Error converting data type varchar to numeric.
PS : I'm surprised with this error since I don't see any varchar data type in my source table.
Source Table(NOR_LABOR) columns and data types
Sample Source Table : http://www.sqlfiddle.com/#!18/bd4fb/1
Destination Table(ALL_LABOR_DETAILS) columns and data types
Sample Destination Table : http://www.sqlfiddle.com/#!18/7eb72/1
Imports System.Configuration
Imports System.Data.SqlClient
Public Class DataCollector
Dim con1, con2 As New SqlConnection
Dim timer1 As Timers.Timer
Dim p_oConn As New Wisys.AllSystem.ConnectionInfo
Protected Overrides Sub OnStart(ByVal args() As String)
con1 = New SqlConnection("Data Source=NORMAC-CTMS\SQLEXPRESS;Database=Normac Data;Integrated Security=true")
Try
con1.Open()
Catch ex As Exception
FileIO.WriteLog(ex.Message)
End Try
con2 = New SqlConnection("Data Source=STLEDGSQL01;Database=MES_DEV;Integrated Security=true")
Try
con2.Open()
Catch ex As Exception
FileIO.WriteLog(ex.Message)
End Try
timer1 = New Timers.Timer()
timer1.Interval = 5000
AddHandler timer1.Elapsed, AddressOf OnTimedEvent
timer1.Enabled = True
FileIO.WriteLog("Service has started")
End Sub
Protected Overrides Sub OnStop()
timer1.Enabled = False
FileIO.WriteLog("Service has stopped")
con1.Close()
con2.Close()
End Sub
Private Sub OnTimedEvent(obj As Object, e As EventArgs)
Dim cmd1, cmd2, cmd3 As SqlCommand
'Connecting the Normac Data table
Dim da1 As SqlDataAdapter = New SqlDataAdapter("select ID, RTRIM(trx_date), RTRIM(work_order), RTRIM(department), RTRIM(work_center), RTRIM(operation_no), RTRIM(operator), RTRIM(total_labor_hours), RTRIM(feet_produced), RTRIM(item_no), RTRIM(posted), RTRIM(lot_no), RTRIM(default_bin) from NOR_LABOR where ID > 46006 order by ID", con1)
Dim cb1 As SqlCommandBuilder = New SqlCommandBuilder(da1)
Dim dt1 As DataTable = New DataTable()
da1.Fill(dt1)
Dim i As Integer
'Inserting Normac Data into ALL_LABOR_DETAILS table
For Each dr As DataRow In dt1.Rows
Try
cmd1 = New SqlCommand("Insert into ALL_LABOR_DETAILS values('" & dr(0) & "','" & dr(1) & "','" & dr(2) & "','" & dr(3) & "','" & dr(4) & "','" & dr(5) & "','" & dr(6) & "','" & dr(7) & "','" & dr(8) & "','" & dr(9) & "','" & dr(10) & "','','','','','" & dr(11) & "','" & dr(12) & "','','','','','','','')", con2)
i = cmd1.ExecuteNonQuery()
FileIO.WriteLog("Most Recent Normac ID " & mostRecentNormacID)
Catch ex As Exception
FileIO.WriteLog(ex.Message)
End Try
Next
da1.Update(dt1)
cmd1.Dispose()
dt1.Dispose()
da1.Dispose()
End Sub
End Class
I'm surprised with this error
You shouldn't be; every single one of the SQL Injection Hacking prone values you've concatenated into your INSERT statement, is a varchar, because theyre surrounded with ''.
Don't just surround every value in any SQL you ever write, with ''
--no
SELECT * FROM Person WHERE Age = '32'
--yes
SELECT * FROM Person WHERE Age = 32
As to your actual problem, you should properly parameterize your insert SQL and set the parameter types accurately. Do the setup of the command once:
cmd1 = New SqlCommand("Insert into ALL_LABOR_DETAILS (ID, trx_date, work_order ...) values(#p0, #p1, #p2 ...)")
cmd1.Parameters.Add("#p0", SqlDbType.Int)
cmd1.Parameters.Add("#p1", SqlDbType.DateTime) 'if it's a datetime2 with a scale, use the overload that accepts a SqlParameter, and do a New With to set the scale
cmd1.Parameters.Add("#p2", SqlDbType.VarChar)
...
Then inside the loop repeatedly set new values and Execute the command:
cmd1.Parameters("#p0").Value = dr(0) 'or whatever dr index you want ID to be
cmd1.Parameters("#p1").Value = dr(1) 'or whatever dr index you want trx_date to be
cmd1.Parameters("#p2").Value = dr(2) 'or whatever dr index you want work_order to be
...
Name all the columns you want to insert to, after the table name in your INSERT, that way you don't have to insert loads of dummy values
.. or perhaps consider using an SqlCommandBuilder to create the INSERT for you from the table definition
This should do it, including fixing a few poor practices, especially the SQL injection issue! Don't forget to set the correct types and lengths for your actual database table in the appropriate place in this code (there's a comment pointing it out).
Imports System.Configuration
Imports System.Data.SqlClient
Public Class DataCollector
Dim conString1 As String = "Data Source=NORMAC-CTMS\SQLEXPRESS;Database=Normac Data;Integrated Security=true"
Dim conString2 As String = "Data Source=STLEDGSQL01;Database=MES_DEV;Integrated Security=true"
Dim timer1 As Timers.Timer
Protected Overrides Sub OnStart(ByVal args() As String)
timer1 = New Timers.Timer()
timer1.Interval = 5000
AddHandler timer1.Elapsed, AddressOf OnTimedEvent
timer1.Enabled = True
FileIO.WriteLog("Service has started")
End Sub
Protected Overrides Sub OnStop()
timer1.Enabled = False
FileIO.WriteLog("Service has stopped")
End Sub
Private Sub OnTimedEvent(obj As Object, e As EventArgs)
Dim sql1 As String = "
SELECT ID, RTRIM(trx_date), RTRIM(work_order), RTRIM(department),
RTRIM(work_center), RTRIM(operation_no), RTRIM(operator),
RTRIM(total_labor_hours), RTRIM(feet_produced), RTRIM(item_no),
RTRIM(posted), RTRIM(lot_no), RTRIM(default_bin)
FROM NOR_LABOR
WHERE ID > 46006
ORDER BY ID ;
"
Dim sql2 As String = "
INSERT INTO ALL_LABOR_DETAILS
VALUES
(#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9, #p10, #p11, #p12);
"
Dim dt As new DataTable
Try
Using cn As New SqlConnection(conString1), _
cmd As New SqlCommand(sql1, cn), _
da As New SqlDataAdapter(cmd)
da.Fill(dt)
End Using
Using cn As New SqlConnection(conString2), _
cmd As New SqlCommand(sql2, cn)
'Use actual types and lengths from the DB here!
cmd.Parameters.Add("#p0", SqlDbType.Int)
cmd.Parameters.Add("#p1", SqlDbType.Int)
cmd.Parameters.Add("#p2", SqlDbType.Int)
cmd.Parameters.Add("#p3", SqlDbType.Int)
cmd.Parameters.Add("#p4", SqlDbType.Int)
cmd.Parameters.Add("#p5", SqlDbType.Int)
cmd.Parameters.Add("#p6", SqlDbType.Int)
cmd.Parameters.Add("#p7", SqlDbType.Int)
cmd.Parameters.Add("#p8", SqlDbType.Int)
cmd.Parameters.Add("#p9", SqlDbType.Int)
cmd.Parameters.Add("#p10", SqlDbType.Int)
cmd.Parameters.Add("#p11", SqlDbType.Int)
cmd.Parameters.Add("#p12", SqlDbType.Int)
cn.Open()
For Each row As DataRow In dt.Rows
For i As Integer = 0 To 12
cmd.Parameters($"#p{i}").Value = row(i)
Next i
cmd.ExecuteNonQuery()
FileIO.WriteLog($"Most Recent Normac ID {row(0)}")
Next row
End Using
Catch ex As Exception
FileIO.WriteLog(ex.Message)
End Try
End Sub
End Class
I'm making a system by using Visual Studio Express 2012 and use the Microsoft SQL Server that already have in visual studio I think. My problem is, when i'm trying to run my system,an error occur said "Operator '&' is not defined for types 'String' and 'System.Windows.Forms.DataGridView'." This is my code.
Imports System.Data.SqlClient
Public Class Registration
Dim cn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\user_PC\Desktop\For FYP\Computer Lab Requirement System\FYP3\FYP3\FYP.mdf;Integrated Security=True")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Private Sub Registration_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cmd.Connection = cn
End Sub
Private Sub btnRegisterL_Click(sender As Object, e As EventArgs) Handles btnRegisterL.Click
If txtIDL.Text <> "" And txtUsernameL.Text <> "" And txtPasswordL.Text <> "" Then
cn.Open()
cmd.CommandText = "update info set id = '" & txtIDL.Text & "',user = '" & txtUsernameL.Text & "',pass = '" & txtPasswordL.Text & "'where id = '" & Form1.DataGridView1 & "' "
cmd.ExecuteNonQuery()
cn.Close()
txtIDL.Text = ""
txtUsernameL.Text = ""
txtPasswordL.Text = ""
End If
End Sub
End Class
I'm glad if there is some one could help me to explain and teach me about whats wrong with my coding above. I'm new in this thing. Thanks. :)
You could hold the Primary Key of your data in your GridView in one of the columns and then use that in your query, instead of the below line that you have:
"'where id = '" & Form1.DataGridView1 & "' "
Im working on a project. Our system is Hotel Reservation. In VB it says that it added in my database
but then when I check my database there is none.
What is the problem
btw Here's the code:
Public Class RegistrationForm
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
qry = "INSERT INTO tblGuest(GuestName, Gender, Address)VALUES('" &
txtName.Text & "','" &
txtGender.Text & "','" &
txtAddress.Text & "');"
cmd = New OleDb.OleDbCommand(qry, con)
dr = cmd.ExecuteReader()
MsgBox("Succesfully added in database")
RoomInfoForm.Show()
End Sub
Private Sub RegistrationForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
koneksyon()
End Sub
End Class
Just because your MsgBox fires doesn't mean the query did what you expect.
This is more like what you want to do:
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
'parameterize the query to avoid SQL injection attacks which is the #1 code vulnerability on OWASP Top 10
Dim qry As String = "INSERT INTO tblGuest(GuestName, Gender, Address)VALUES(?, ?, ?);"
'Put disposable resources within Using blocks
Using con As New OleDb.OleDbConnection()
Using cmd As New OleDb.OleDbCommand(qry, con)
'Create the parameters.
Dim paramName As New OleDb.OleDbParameter("#p1", OleDb.OleDbType.VarChar)
paramName.Value = txtName.Text 'you should null check and validate all these textbox values
Dim paramGender As New OleDb.OleDbParameter("#p2", OleDb.OleDbType.VarChar)
paramGender.Value = txtGender.Text
Dim paramAddress As New OleDb.OleDbParameter("#p3", OleDb.OleDbType.VarChar)
paramAddress.Value = txtAddress.Text
'Assign the parameters to the command
cmd.Parameters.Add(paramName)
cmd.Parameters.Add(paramGender)
cmd.Parameters.Add(paramAddress)
'you are not returning a result set from the command, so ExecuteNonQuery
cmd.ExecuteNonQuery()
End Using
End Using
MsgBox("Succesfully added in database")
RoomInfoForm.Show()
End Sub
I tried out to connect my database(ms-access) to Visual basic.But it came up with the following error:
A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
If there is a handler for this exception, the program may be safely continued.
I used the following code.please see if there is any error..please help me out for it..
The Code is:
Private Sub frmGive_Load(sender As Object, e As EventArgs) Handles Me.Load
con = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\Users\AntivirUS Vandry\Documents\Visual Studio 2013\Projects\Give And Get\dbaseMain.mdb")
Dim sql As String = "Select * from tblGive"
Dim dbcmd As OleDbCommand = New OleDbCommand(sql, con)
con.Open()
Dim dbadapter As OleDbDataAdapter = New OleDbDataAdapter(sql, con)
Dim db As DataSet = New DataSet("TABLE")
dbadapter.Fill(db, "TABLE")
'create new instance of table so that row can be accessed
Dim dt As New DataTable
dt = db.Tables("TABLE")
CmbGenre.Text = dt.Rows(0)(0)
CmbLanguage.Text = dt.Rows(0)(1)
txtNMovie.Text = dt.Rows(0)(2)
txtFName.Text = dt.Rows(0)(3)
txtLname.Text = dt.Rows(0)(4)
CmbClass.Text = dt.Rows(0)(5)
txtnull.Text = dt.Rows(0)(6)
End Sub
There are some codes in between them.Including textboxes and combo boxes.
Public Sub submit()
con = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\Users\AntivirUS Vandry\Documents\Visual Studio 2013\Projects\Give And Get\dbaseMain.mdb")
con.Open()
Dim sql As String
sql = "Insert into tblGive (Genre,Language,NMovie,FName,LName,Class,SaveDate)" + "VALUES (" & CmbGenre.Text & "','" & CmbLanguage.Text & "','" & txtNMovie.Text & "','" & txtFName.Text & "','" & txtLname.Text & "','" & CmbClass.Text & "','" & txtnull.Text & "')"
MsgBox(sql)
Dim dbcmd As OleDbCommand
dbcmd = New OleDbCommand(sql, con)
dbcmd.ExecuteNonQuery()
MsgBox("Saved")
End Sub
You are missing a single quote at the beginning of the values keyword.
In other words,
VALUES (" & CmbGenre.Text & "','" & CmbLanguage.Text &
should be
VALUES ('" & CmbGenre.Text & "','" & CmbLanguage.Text &
I need to insert a row into the Access table. I have been getting
object reference not set to instance of an object
My code is:
Private Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim strconstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb"
Dim objcon As OleDb.OleDbConnection
objcon = New OleDb.OleDbConnection(strconstring)
Dim objcommand As OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Try
objcon.Open()
Dim command As String
command = "insert into Artists(Artist, Company, Sales )" _
& " values('" & ArtistBox.Text & "', '" _
& TextBox2.Text & "', " & TextBox3.Text & ")"
objcommand = New OleDb.OleDbCommand(command, objcon)
da.InsertCommand.CommandText = command
da.InsertCommand.ExecuteNonQuery()
Catch exceptionobject As Exception
MessageBox.Show(exceptionobject.Message)
Finally
objcon.Close()
End Try
End Sub
Your connection string is a bit of a mess, so that may be causing the problem. Use EITHER...
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb;
...OR...
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Daisy\My Documents\Downloads\MusicSales.mdb;