am using vb.net, and i want to insert a row to my db Table "adwPays" from my windows form.
this is my code:
Dim CC, EngName, FreName, LanCode As String
Dim DialCode As Integer
CC = txtCC.Text
EngName = txtEN.Text
FreName = txtFN.Text
LanCode = txtLC.Text
DialCode = txtDC.Text
Dim MyConn As New SqlConnection("Server=(local);Database=dbAjout;Integrated Security=True")
Dim query As String
query = "INSERT INTO adwPays (CC, Anglais,Francais,CodeLangue,IndicInter) VALUES ( ' " & CC & "','" & EngName & "','" & FreName & "','" & LanCode & "','" & DialCode & " ');"
Dim cmd As New SqlCommand(query, MyConn)
MyConn.Open()
cmd.ExecuteScalar()
MyConn.Close()
BUT its giving me this error
"An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: String or binary data would be truncated.
The statement has been terminated."
any help?
Use a parameterized query like this
Dim query = "INSERT INTO adwPays (CC, Anglais,Francais,CodeLangue,IndicInter) " &
"VALUES (#cc, #ename, #fname, #lan, #dial)"
Using MyConn = New SqlConnection("Server=(local);Database=dbAjout;Integrated Security=True")
Using cmd = New SqlCommand(query, MyConn)
cmd.Parameters.AddWithValue("#cc", CC)
cmd.Parameters.AddWithValue("#ename", EngName)
cmd.Parameters.AddWithValue("#fname", FreName)
cmd.Parameters.AddWithValue("#lan", LanCode)
cmd.Parameters.AddWithValue("#dial", DialCode)
MyConn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Using a parameterized query allows to avoid problems with Sql Injections and clears the command text from the formatting quotes around strings and dates and also let the framework code pass the correct decimal point for the numeric types when need
I have also added a Using Statement around the SqlConnection and the SqlCommand to be sure that the objects are closed and destroyed. The parameters are all passed as strings, this could be wrong if any of your database fields are not of text type.
It sounds like you have a String value that is longer than the database type size allows. Can you verify the type and size of each of the following fields:
cc
ename
fname
lan
Now cross-reference those sizes with what the values are in the textbox fields you are pulling them from in the UI.
My money is on one of those exceeding the database size limits.
If that is the case, then you need to introduce length checking before you attempt to save to the database.
Related
Good morning,
I am having trouble understanding the # parameter in vb.net. if we take the example code for the msdn:
' Update the demographics for a store, which is stored
' in an xml column.
Dim commandText As String = _
"UPDATE Sales.Store SET Demographics = #demographics " _
& "WHERE CustomerID = #ID;"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(commandText, connection)
' Add CustomerID parameter for WHERE clause.
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
' Use AddWithValue to assign Demographics.
' SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("#demographics", demoXml)
There seem to be no problem at all, however when you try to add more parameters into the mix, it does not seems to work. What would be the correct syntax to add more than one parameter?
Here is my piece of code:
query &= "INSERT INTO "
query &= imageProcAlgo.GetSqlTable()
query &= " ( #dateTimeStampCol , #numberOfBlobsCol , #AvgLengthCol , #avgWidthCol ) "
query &= "Values (#dtsvalue, #nbOfBlobsValue, #avgLengthValue, #avgWidthValue)"
and here where I try to add values to those parameters:
Using conn As New SqlConnection(connectStr)
Using comm As New SqlCommand(query)
With comm
.Connection = conn
.CommandType = CommandType.Text
.Parameters.AddWithValue("#dateTimeStampCol", "DateTimeStamp")
.Parameters.AddWithValue("#numberOfBlobsCol", "NumberOfBlob")
.Parameters.AddWithValue("#AvgLengthCol", "AvgWidth")
.Parameters.AddWithValue("#avgWidthCol", "AvgLength")
.Parameters.AddWithValue("#dtsvalue", "CURRENT_TIMESTAMP")
.Parameters.AddWithValue("#nbOfBlobsValue", imageProcAlgo.GetnumberOfBlobs().ToString())
.Parameters.AddWithValue("#avgLengthValue", imageProcAlgo.GetAvgWidth())
.Parameters.AddWithValue("#avgWidthValue", imageProcAlgo.GetAvgLength())
End With
Try
conn.Open()
comm.ExecuteNonQuery()
conn.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message.ToString(), "Error Message")
End Try
End Using
When I try to execute this piece of code, I get an error saying that #datetimestampcol and so on are not valid column names.
I don't seem to understand what is the difference between the MSDN anf my code but i feel pretty close.. Any pointers for me to understand a bit better? to figure out where I went wrong?
Thanks,
no_hp = TextBox1.Text
alamat = TextBox2.Text
password = TextBox3.Text
cmd = New OleDbCommand("UPDATE [user] SET no_hp = '" & CInt(TextBox1.Text) & "',alamat = " & TextBox2.Text & ", pin ='" & CInt(TextBox3.Text) & "' WHERE id = " & id & "", conn)
cmd.Connection = conn
cmd.ExecuteReader()
i was trying to update my access database with the following error
i cant seem to see where i did wrong
i already changed the data type from the textbox to match with the data types used in the database
the no_hp and pin is integer so i converted it to Cint but it doesnt seem to work
i already tried to substitute it to a variable but still it didnt work
please tell me where i did wrong
Use Parameters to avoid SQL injection, a malious attack that can mean data loss. The parameter names in Access do not matter. It is the order that they are added which must match the order in the SQL statement that matters.
The Using...End Using statements ensure that you objects are closed and disposed even it there is an error. This is most important for connections.
You con't need to set the connection property of the command because you passed the connection in the constructor of the command.
ExcuteReader is for retrieving data. Use ExecuteNonQuery to update, insert of delete.
Private Sub UpdateUsers()
Using conn As New OleDbConnection("Your connection string")
Using cmd = New OleDbCommand("UPDATE [user] SET no_hp = ?,alamat = ?, pin =? WHERE id = ?", conn)
cmd.Parameters.Add("nohp", OleDbType.Integer).Value = CInt(TextBox1.Text)
cmd.Parameters.Add("alamat", OleDbType.VarChar).Value = TextBox2.Text
cmd.Parameters.Add("pword", OleDbType.Integer).Value = CInt(TextBox3.Text)
cmd.Parameters.Add("id", OleDbType.Integer).Value = id
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
I want to get this sentence stored in SQL.
"WorkForceNow (WFN): Production: DS work for new schema on Training Farm"
My Insertion Code :
Dim sqq, sqq1 As New SqlConnection
sqq.ConnectionString = "##Conection string##"
sqq.Open()
Dim sqq2 As String = "Insert into [Reviews] values('" & TextBox1.Text & "')"
Dim cmd1 As New SqlCommand(sqq2, sqq)
cmd1.ExecuteNonQuery()
sqq.Close()
Error :
String or binary data would be truncated. The statement has been
terminated.
How to ignore special symbols in SQL?
what i got:
two mdb databases and one application to insert information (rows) from db1 to db2.
when i'am runing my code there is an exception:
System resource exceeded.
the code:
Connection Strings:
Dim db2Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\db2.mdb;Persist Security Info=False;")
Dim db1Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\db1.mdb;Persist Security Info=False;")
Code to copy the information:
Dim DataAddapter As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
'Open DB1 Connection:
db1Connection.open()
'Select All From M
DataAddapter.SelectCommand = New OleDb.OleDbCommand("SELECT * FROM M", db1Connection)
Dim cmd As OleDb.OleDbCommand = DataAddapter.SelectCommand
Dim Reader As OleDb.OleDbDataReader = cmd.ExecuteReader()
'Before Reading Results From DB1 Lets Open DB2Connection:
db2Connection.open()
'Start Reading Results in LOOP:
Do Until Reader.Read() = False
Dim F_Name As String = Reader("F_NAME")
Dim L_Name As String = Reader("L_NAME")
Dim CITY As String = Reader("NAME_CITY")
F_Name = Replace(F_Name, "'", "")
L_Name = Replace(L_Name, "'", "")
'Start Moving The Results To Db2(Insert):
'--------------------------------------
Dim Exist As Integer = 0
Dim c As New OleDb.OleDbCommand
c.Connection = db2Connection
c.CommandText = "SELECT COUNT(*) FROM `Names` WHERE `LastName`='" & L_Name & "' AND `FirstName`='" & F_Name & "' AND `City`='" & CITY & "'"
'----------------------------------------
'Exception Here!! :(
'This Line Checking If Already Exist
Exist = CLng(c.ExecuteScalar())
'----------------------------------------
If Exist = 0 Then
c.CommandText = "INSERT INTO `Names` (`LastName`,`FirstName`,`City`) VALUES ('" & L_Name & "','" & F_Name & "','" & CITY & "')"
c.ExecuteNonQuery()
'Note: After this line i'am getting the Exception there... (2 queries executed ExecuteScalar + ExecuteNonQuery) maybe i need to create connection for every query? :S
End If
Loop
another thing:
i have to send the query to db2 in this syntax(Otherwise it does not work):
INSERT INTO `Names` (`LastName`,`FirstName`,`City`) VALUES ('" & L_Name & "','" & F_Name & "','" & CITY & "')
i have to use the -> ` <- to the name of the columns,
but when i'am sending a query to db1 without -> ` <- it's working. :S and i dont know what is the difference between db1 to db2 but its very strange maybe my problem is there...
good answer is a good example plus good explanation :).(c# or vb.net)
You are prime for sql-injection... You should read-up on that, and at a minimum, PARAMETERIZE your sql commands, do NOT build string statement to execute with embedded values. I don't specifically know how db2 handles parameters... some use "?" as place-holders, SQL-Server uses "#" and Advantage Database uses ":".. but in either case, here is the principle of it...
c.CommandText = "select blah from `names` where LastName = ? and FirstName = ? and City = ?"
c.CommandText = "select blah from `names` where LastName = #parmLastName and FirstName = #parmFirstName and City = #parmCity"
For the named parameters above (such as #parmLastName), I am prefixing with "parm" for sole purpose of differentiating a value vs the actual COLUMN name
Then, your parameters would be something like
c.Parameters.Add( "#parmLastName", yourLastNameVariable )
c.Parameters.Add( "#parmFirstName", yourFirstNameVariable)
c.Parameters.Add( "#parmCity", yourCityVariable)
If using the "?" version of parameters where they are not explicitly named, you need to just make sure your parameter context is in the same sequence as the "?" place-holders.
Then execute your call... Same principle would apply for all your queries (select, insert, update, delete)
As for your system resources... how many records are you pulling down. It could just be choking your system memory resources trying to pull down the entire database table. You might want to break down based on one alphabetic letter at a time...
Also, a link from MS about system resources and Access via a patch.
Trying to select an integer from an Access Database using an SQL statement in VB
Dim cmdAutoTypes As New OleDbCommand
Dim AutoTypesReader As OleDbDataReader
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = '" & cboTypeIds.Text & "'"
AutoTypesReader = cmdAutoTypes.ExecuteReader
Error message says: "OleDbException was unhandled: Data type mismatch in criteria expression." and points to the AutoTypesReader = cmdAutoTypes.ExecuteReader line
Rather make use of OleDbParameter Class
This will also avoid Sql Injection.
You don't need the quotes in the query string. You're searching for a number, not a string.
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text
Hi In access SQL you can't use single quote around your Integer type.
so
command text will be.. "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text & " and .... "
In Access SQL, don't quote numeric constants.
And test whether IsNull(cboTypeIds). You can't do what you were planning to do until a value has been chosen.
Do not use string concatenation when you build your SQL query, use parameters instead.
Dim cmd As OledbCommand = Nothing
Dim reader as OleDbDataReader = Nothing
Try
Dim query As String = "SELECT * FROM AutoTypes WHERE TypeId = #Id"
cmd = New OledbCommand(query, connection)
//adding parameter implicitly
cmd.Parameters.AddWithValue("#Id", cboTypeIds.Text)
reader = cmd.ExecuteReader()
Catch ex As Exception
Messagebox.Show(ex.Message, MsgBoxStyle.Critical)
End Try
You can also explicitly state the parameter data type.
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = cboTypeIds.Text
Hope this helps.