I have problem with database save changes:
coon1.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & _
"magazyn.mdb"
sql = "INSERT INTO magazyn (ID_Towaru,Kod_Towaru,Nazwa_Towaru,Ilość_w_magazynie,ilość_minimalna,ALERT) VALUES ('" & jakiid & "','" & kodtowaru & "','" & nazwatowaru & "','" & iloscwmagazynie & "','" & iloscminimalna & "',0)"
Dim MyConnection As New OleDbConnection(conn)
Dim command1 As New OleDbCommand(sql, MyConnection)
command1.Connection.Open()
command1.ExecuteNonQuery()
MyConnection.Close()
I try add new record to table magazyn, but when opened database with Access then I didn't see any new record related to magazyn in the table. But ViewGrid shows me this new element until I close and re-open the program.
Does someone know where the problem is?
Always use parameters and not string concatenation. This rule should be followed categorically
sql = "INSERT INTO magazyn " +
"(Kod_Towaru,Nazwa_Towaru,Ilość_w_magazynie,ilość_minimalna,ALERT) " +
"VALUES (?, ?, ?, ?,0)"
Using MyConnection As New OleDbConnection(conn)
Using command1 As New OleDbCommand(sql, MyConnection)
command1.Connection.Open()
command1.Parameters.AddWithValue("#Kod", kodtowaru)
command1.Parameters.AddWithValue("#naz", nazwatowaru)
command1.Parameters.AddWithValue("#ilo", iloscwmagazynie)
command1.Parameters.AddWithValue("#mini", iloscminimalna)
command1.ExecuteNonQuery()
End Using
End Using
This, of course, requires that the variables used as value for the parameters are of the correct datatype.
Please Insert This Below Coding in Module.
Imports System.Data.OleDb
Module Module1
Public OleCn As New OleDbConnection()
Public Function StrConnection() As String
StrConnection = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Testing.Accdb;"
Return StrConnection
End Function
After This Insert the Below Coding in Save Button.
Dim msg As DialogResult = MessageBox.Show("Do you want to Save this Record? ", "Response", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If (msg = vbYes) Then
If RequiredEntry() = True Then
Return
End If
Try
With OleCn
If .State <> ConnectionState.Open Then
.ConnectionString = StrConnection()
.Open()
End If
End With
Catch ex As Exception
MessageBox.Show(ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Try
Dim sSQL As String = "insert into Vendor values(#VendorCode,#VendorName,#Address,#City,#LandPhone,#Mobile,#EmailID,#Balance)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, OleCn)
'VendorCode
Dim VendorCode As OleDbParameter = New OleDbParameter("#VendorCode", OleDbType.VarChar, 10)
VendorCode.Value = txtVendorCode.Text.ToString()
cmd.Parameters.Add(VendorCode)
'VendorName
Dim VendorName As OleDbParameter = New OleDbParameter("#VendorName", OleDbType.VarChar, 25)
VendorName.Value = txtVendorName.Text.ToString()
cmd.Parameters.Add(VendorName)
'Address
Dim Address As OleDbParameter = New OleDbParameter("#Address", OleDbType.VarChar, 50)
Address.Value = txtAddress.Text.ToString()
cmd.Parameters.Add(Address)
'City
Dim City As OleDbParameter = New OleDbParameter("#City", OleDbType.VarChar, 25)
City.Value = txtCity.Text.ToString()
cmd.Parameters.Add(City)
'LandPhone
Dim LandPhone As OleDbParameter = New OleDbParameter("#LandPhone", OleDbType.VarChar, 50)
LandPhone.Value = txtLandPhone.Text.ToString()
cmd.Parameters.Add(LandPhone)
'Mobile
Dim Mobile As OleDbParameter = New OleDbParameter("#Mobile", OleDbType.VarChar, 15)
Mobile.Value = txtMobile.Text.ToString()
cmd.Parameters.Add(Mobile)
'EmailID
Dim EmailID As OleDbParameter = New OleDbParameter("#EmailID", OleDbType.VarWChar, 25)
EmailID.Value = txtEmailID.Text.ToString()
cmd.Parameters.Add(EmailID)
'Balance
Dim Balance As OleDbParameter = New OleDbParameter("#Balance", OleDbType.VarWChar, 10)
Balance.Value = txtBalance.Text.ToString()
cmd.Parameters.Add(Balance)
If cmd.ExecuteNonQuery() Then
OleCn.Close()
MessageBox.Show("New Record is Added Successfully.", "Record Saved")
Call clear()
Else
MsgBox("Record Addition Failed ", MsgBoxStyle.Critical, "Addition Failed")
Return
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Data Error")
Exit Sub
End Try
End If
Related
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 am trying to make a query that deletes the user from my database.
But when i confirm to delete the user it gives me an error:
System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "#Username".
Imports System.Data.SqlClient
Public Class DeleteForm
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim RetVal As Integer
Dim conn = New SqlConnection("Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=dbProject;Integrated Security=True")
Using cmd = New SqlCommand("select count(*) from tblLogin where username = #Username and password = #Password", conn)
cmd.Parameters.Add("#Username", SqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtPassword.Text
conn.Open()
If conn.State = ConnectionState.Open Then
RetVal = CInt(cmd.ExecuteScalar)
If RetVal = 1 Then
If txtPassword.Text And txtCheckPassword.Text <> "" Then
If txtCheckPassword.Text = txtPassword.Text Then
Dim cancConf As Integer = MessageBox.Show("This cant be undone!" & vbCrLf & "Are you sure?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
If cancConf = DialogResult.Yes Then
Try
Dim queryDelete As String = "DELETE FROM tblLogin WHERE username = #Username"
Dim cmdDelete As New SqlClient.SqlCommand(queryCancellazione, conn)
cmdCancellazione.ExecuteNonQuery()
MsgBox("Account deleted succesfully!")
cmdCancellazione.Dispose()
conn.Close()
LoginForm.Show()
Me.Close()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
ElseIf cancConf = DialogResult.No Then
End If
Else
MsgBox("The passwords arent matching!", MsgBoxStyle.Exclamation)
End If
ElseIf txtPUtenteCANC.Text <> "" And txtPUtenteCONF.Text = "" Then
MsgBox("Please, confirm the password")
End If
Else
MsgBox("User not found!", MsgBoxStyle.Exclamation)
txtNUtenteCANC.Clear()
txtPUtenteCANC.Clear()
txtPUtenteCONF.Clear()
txtNUtenteCANC.Select()
End If
Else
MessageBox.Show("The connection is not open!" & vbCrLf & "The program will close", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End
End If
End Using
End Sub
End Class
You have added that parameter to the SELECT COUNT command but not to the DELETE command.
Dim queryCancellazione As String = "DELETE FROM tblLogin WHERE username = #Username"
Dim cmdCancellazione As New SqlClient.SqlCommand(queryCancellazione, conn)
cmdCancellazione.Parameters.Add("#Username", SqlDbType.VarChar).Value = txtUsername.Text
I'm doing a program and I'm in a part that I need to create users in the database in access. But after entering the data and clicking the create user button it gives me an error. If you add users to the database it works but if you try to add it by the program's the result is a syntax error
Else
Try
Dim myconnection As OleDbConnection
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Software_Simples\Software\DataBase.accdb"
myconnection = New OleDbConnection(constring)
myconnection.Open()
Dim sqlQry As String
'sqlQry = "INSERT INTO Usernames(Username, Password) VALUES(" & TextBox2.Text & "," & TextBox3.Text & ")"
sqlQry = "INSERT INTO Usernames(ID_User, Username, Password) VALUES(Null,TextBox2.Text,TextBox3.Text )"
Dim cmd As New OleDbCommand(sqlQry, myconnection)
cmd.ExecuteNonQuery()
myconnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'Fechar
Me.Close()
MessageBox.Show("Utilizador criado com suecesso: " & username_create, "Aviso", MessageBoxButtons.OK)
End If
There are at least three problems in your code:
1) Password is a reserved keyword. Needs to be between square brackets
2) String values when passed to a database need to be between single quotes, but.. see point 3
3) Use parameters instead of string concatenation (what if password contains a single quote?)
4) Dispose the disposable object like the connection and the command.
So rewriting it
Dim constring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Software_Simples\Software\DataBase.accdb"
Dim sqlQry = "INSERT INTO Usernames(Username, [Password]) VALUES(#name, #pwd)"
Try
Using myconnection = New OleDbConnection(constring)
Using cmd As New OleDbCommand(sqlQry, myconnection)
myconnection.Open()
cmd.Parameters.Add("#name", OleDbType.VarWChar).Value = TextBox2.Text
cmd.Parameters.Add("#pwd", OleDbType.VarWChar).Value = TextBox3.Text
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
It should read:
sqlQry = "INSERT INTO Usernames (ID_User, Username, [Password]) VALUES (Null,'" + TextBox2.Text + "','" + TextBox3.Text + "')"
I have a button but it can save duplicate entries i don't know how to correctly put a if not exist operator pls help..
cmd = New SqlCommand("INSERT INTO Students(Familyname,Firstname,Middlename,StudentID)VALUES('" & txtname.Text & "','" & txtfname.Text & "','" & txtmname.Text & "','" & txtid.Text & "')", cn)
cn.Open()
i = cmd.ExecuteNonQuery
cn.Close()
If txtname.Text <> "" Then
ElseIf i > 0 Then
MsgBox("Save Sucessfully!", MessageBoxIcon.Information, "Success")
showrecord()
clear()
Else
MsgBox("Save Failed!", MessageBoxIcon.Error, "Error")
End If
You can use NOT EXISTS to prevent duplicate insert:
Dim sql = "INSERT INTO Students(Familyname, Firstname, Middlename, StudentID) " & _
"VALUES(#FamilyName, #Firstname, #Middlename, #StudentID)" & _
"WHERE NOT EXISTS(SELECT 1 FROM Students WHERE StudentId = #StudentID)"
Using cn As New SqlConnection("Your connection string here")
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Parameters.Add("#FamilyName", SqlDbType.VarChar, 50).Value = txtname.Text
cmd.Parameters.Add("#Firstname", SqlDbType.VarChar, 50).Value = txtfname.Text
cmd.Parameters.Add("#Middlename", SqlDbType.VarChar, 50).Value = txtmname.Text
cmd.Parameters.Add("#StudentID", SqlDbType.VarChar, 50).Value = txtid.Text
Dim i = cmd.ExecuteNonQuery
End Using
You should always use parameterized queries to avoid SQL Injection attacks.
NOTE: Please apply appropriate field types.
Try this one :
cn.Open()
Dim intReturn as integer
Dim strSql as string = "Select * from Students where StudentID = #StudentID"
sqlcmd = new sqlcommand(strSql, cn)
With sqlcmd.parameters
.addwithvalue("#StudentID", ctype(txtid.text,string)
End with
intReturn = sqlcmd.ExecuteScalar
If(intReturn > 0)
cmd = New SqlCommand("INSERT INTO Students(Familyname,Firstname,Middlename,StudentID)VALUES('" & txtname.Text & "','" & txtfname.Text & "','" & txtmname.Text & "','" & txtid.Text & "')", cn)
i = cmd.ExecuteNonQuery
If txtname.Text <> "" Then
ElseIf i > 0 Then
MsgBox("Save Sucessfully!", MessageBoxIcon.Information, "Success")
showrecord()
clear()
Else
MsgBox("Save Failed!", MessageBoxIcon.Error, "Error")
End If
Else
MsgBox("Student Already Exist", MessageBoxIcon.Error, "Error")
End If
cn.Close()
And don't forget to make your StudentID field as Unique in your database.
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 &