When I try to update my databse table, what should I do?
Why am I getting this error?
it's because mismatched datatype inserted to your columns
change update query to be like this
update Hasil_Rml_Hallo_Bro SET Nilai_Error=" & Label3.text & " WHERE ID=" & label4.text
remove the "'" apostrophe letter
Make sure that your column in your database has the same data type which you are inserting into it.
Always use Parameters
Dim query As String = "update Hasil_Rml_Hallo_Bro SET Nilai_Error= #Error WHERE ID=#Id"
Using connection As New OleDbConnection(connectionString)
Using command As New OleDbCommand(query, connection)
Dim errorParameter As New OleDbParameter With
{
.ParameterName = "#Error",
.OleDbType = OleDbType.VarChar, // Or what is correct type in database
.Value = Label3.text
}
Dim idParameter As New OleDbParameter With
{
.ParameterName = "#Id",
.OleDbType = OleDbType.Integer, // Or what is correct type in database
.Value = Integer.Parse(label4.text) // Convert to correct type if needed
}
command.Parameters.Add(errorParameter, idParameter)
connection.Open()
command.ExecuteNonQuery()
End Using
End Using
Notice that you need put correct type for the parameter - same as column type you are using.
Related
Currently I'm developing a student portal with an appropriate and simple login system for my college's final year project purpose. This is one of the command button (to save photo to SQL server) I've encountered error. This is the error statement:
System.Data.SqlClient.SqlException: 'String or binary data would be truncated.
The statement has been terminated.'
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
'String imagelocation = ""
Dim images() As Byte = Nothing
'Dim imagelocation As String
'imagelocation = ""
Dim Stream As New FileStream(imagelocation, FileMode.Open, FileAccess.Read)
Dim brs As New BinaryReader(Stream)
images = brs.ReadBytes(CInt(Stream.Length))
Dim source As String = "Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True"
Dim con As New SqlConnection(source)
con.Open()
Dim cmd As String = "Insert into Photo Values('" + TextBox2.Text + "', #images)"
Dim qry As New SqlCommand(cmd, con)
qry.Parameters.Add(New SqlParameter("#images", images))
'qry.Parameters.Add(new SqlParameter("#images", pictureBox1));
***Dim i As Integer = qry.ExecuteNonQuery()
If i >= 1 Then
MessageBox.Show("Successfull!", "message", MessageBoxButtons.OK)
Else
MessageBox.Show("Fail!", "message", MessageBoxButtons.OK)
End If
End Sub
End Class
This is a SQL table for me to save the uploaded photo into database. Any help would be appreciated. Thanks.
UPDATE
PreviouslyPhotocolumn name changed toImg, Photowould be the table name.
So I tried to switch the code into another method which is:
Dim source As String = "Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True"
Dim con As New SqlConnection(source)
Dim command As New SqlCommand("Insert into Photo (Img, Pname) Values (#Img, #Pname)", con)
Dim ms As New MemoryStream
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat)
command.Parameters.Add("#Img", SqlDbType.Image).Value = ms.ToArray()
command.Parameters.Add("#Pname", SqlDbType.VarChar).Value = TextBox2.Text
con.Open()
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("Successfully uploaded", "Message", MessageBoxButtons.OK)
Else
MessageBox.Show("Failed. Try again.", "Message", MessageBoxButtons.OK)
End If
So it's actually worked I guess. Not sure if there would be any hidden error. Any comment would be helpful guys. This is the output of Photo table.
Phototable output
This error occurs when you specify a the size of a parameter and then provide data that is larger than that. For a start, the way you're adding the parameter is bad:
qry.Parameters.Add(New SqlParameter("#images", images))
You're not specifying a data type or a size there so you're relying on the system default type being OK. Obviously it is not or you would not be getting this error. ALWAYS specify the data type and, if the data type is variable-size, the size as well, e.g.
qry.Parameters.Add("#images", SqlDbType.VarBinary, 8000).Value = images
The SqlDbType value you specify should match the data type of the column the data is for and the size should match the size in the database too. If you use varbinary(max) in the database then use -1 for the parameter size.
First, you should know that IMAGE data type usage is deprecated. Usage of VARBINARY(MAX) is more recommended:
ALTER TABLE TableName ALTER COLUMN Photo VARBINARY(MAX)
The explanation about image data type deprecation can be seen here.
For storing images you have to make use of the varbinary(MAX)
datatype. The image datatype will be deprecated.
Next, the exception occurred because you're adding data to image column which has smaller size than passed image from parameter (because SqlDbType is not specified, CLR infers Byte(n) type automatically; hence data truncation may occur to fit passed array for IMAGE data type). Use SqlDbType.VarBinary with size set to -1:
qry.Parameters.Add("#images", SqlDbType.VarBinary, -1).Value = images
Note that you can set maximum size of VARBINARY with certain numbers in bytes (other than -1), but you need to check against images.Length to prevent truncation (simply cancel upload process if image size is larger than specified).
If images.Length > 1048576 Then ' maximum limit e.g. 1 MiB
' cancel upload
Else
' continue and save to DB
End If
Finally, adjust the query to use parameters for all values:
Dim source As String = "Data Source=LAPTOP-85ALBAVS\SQLEXPRESS;Initial Catalog=Portal;Integrated Security=True"
Using con As New SqlConnection(source)
con.Open()
Dim cmd As String = "Insert into Photo Values(#pname, #images)"
Using qry As New SqlCommand(cmd, con)
qry.Parameters.Add("#pname", SqlDbType.NVarchar, 50).Value = TextBox2.Text
qry.Parameters.Add("#images", SqlDbType.VarBinary, -1).Value = images
Dim i As Integer = qry.ExecuteNonQuery()
' other stuff
End Using
End Using
I have this code to update my SQL database from data in a textbox, in VB. I need to use parameters in case the text contains a tic mark ,', or a quote ,", etc. Here is what I have:
dbConn = New SqlConnection("server=.\SQLEXPRESS;Integrated Security=SSPI; database=FATP")
dbConn.Open()
MyCommand = New SqlCommand("UPDATE SeansMessage SET Message = '" & TicBoxText.Text & _
"'WHERE Number = 1", dbConn)
MyDataReader = MyCommand.ExecuteReader()
MyDataReader.Close()
dbConn.Close()
And this is my lame attempt to set a parameter from what I have seen on the web, which I don't understand all that well.
dbConn = New SqlConnection("server=.\SQLEXPRESS;Integrated Security=SSPI; database=FATP")
dbConn.Open()
MyCommand = New SqlCommand("UPDATE SeansMessage SET Message = #'" & TicBoxText.Text & _
"'WHERE Number = 1", dbConn)
MyDataReader = MyCommand.ExecuteReader()
MyDataReader.Close()
dbConn.Close()
How do you do this? Cause if there is a ' mark in the textbox when I run the code, it crashes.
You are on the right path to avoiding Bobby Tables, but your understanding of # parameters is incomplete.
Named parameters behave like variables in a programming language: first, you use them in your SQL command, and then you supply their value in your VB.NET or C# program, like this:
MyCommand = New SqlCommand("UPDATE SeansMessage SET Message = #TicBoxText WHERE Number = 1", dbConn)
MyCommand.Parameters.AddWithValue("#TicBoxText", TicBoxText.Text)
Note how the text of your command became self-contained: it no longer depends on the value of the text from the text box, so the users cannot break your SQL by inserting their own command. #TicBoxText became a name of the variable that stands for the value in the text of the command; the call to AddWithValue supplies the value. After that, your ExecuteReader is ready to go.
There are a number of improvements in here:
Using dbConn As New SqlConnection("server=.\SQLEXPRESS;Integrated Security=SSPI; database=FATP"), _
MyCommand As SqlCommand("UPDATE SeansMessage SET Message = #Message WHERE Number = 1", dbConn)
'Make sure to use your exact DbType (ie: VarChar vs NVarChar) and size
MyCommand.Parameters.Add("#Message", SqlDbType.VarChar).Value = TicBoxText.Text
dbConn.Open()
MyCommand.ExecuteNonQuery() ' don't open a data reader: just use ExecuteNonQuery
End Using 'Using block will close the connection for you
I am using the following SQL statement :
Dim strSql5 As String = "SELECT * FROM dbo.ontledings " & _
" where plaasblok = #plaasblokparsversoeke " & _
" and analisedatum = #laastedatum"
cnn.Open()
Dim aksie2 As New SqlClient.SqlCommand(strSql5, cnn)
aksie2.Parameters.Add("#plaasblokparsversoeke", SqlDbType.VarChar).Value = plaasblokparsversoeke
aksie2.Parameters.Add("#laastedatum", SqlDbType.Date).Value = laastedatum
aksie2.ExecuteNonQuery()
cnn.Close()
I want to fill a datatable like so :
Dim dtb5 As New DataTable
dtb5.Clear()
Using cnn As New SqlConnection("Data Source=GIDEON-E-LAPTOP\SQLEXPRESS2014;Initial Catalog=SkeduleringDatabasis;Integrated Security=True")
cnn.Open()
Using dad5 As New SqlDataAdapter(strSql5, cnn)
dad5.Fill(dtb5)
End Using
cnn.Close()
End Using
I get the following error message : Must declare the scalar variable "#plaasblokparsversoeke"
I cannot figure out where and how to declare the scalar variables.
The error occurs at the line : dad5.Fill(dtb5)
Regards
You need to add the parameters like
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#plaasblokparsversoeke", plaasblokparsversoeke.Text)
cmd.Parameters.AddWithValue("#laastedatum", laastedatum.Text)
As correctly commented below, you need to use the Add method to add the paramters:
cmd.Parameters.Add("#plaasblokparsversoeke", SqlDbType.Varchar).Value = plaasblokparsversoekeVariable;
cmd.Parameters.Add("#laastedatum", SqlDbType.Varchar).Value = laastedatumVariable;
Firstly, avoid hard-coding a parameterised query in this way, for avoidance of SQL injection.
To answer your specific question: you are trying to use parameters in the query without having defined them in the SQLCommand.
Have a look at MSDN for the full documentation.
With this query
Dim strSql5 As String = "SELECT * FROM dbo.ontledings " & _
" where plaasblok = #plaasblokparsversoeke " & _
" and analisedatum = #laastedatum"
You are definining 2 SQL variables called #plaasblokparsversoeke and #laastedatum that you have to pass as parameters to your command, like this
command.Parameters.Add("#plaasblokparsversoeke", SqlDbType.Int);
command.Parameters["#plaasblokparsversoeke "].Value = yourValue;
MSDN article on SQL command parameters here
I get the Conversion from type 'DBNull' to type 'Integer' is not valid." error on the line "Dim avgObject As string = Cstr(avgCom.ExecuteScalar())
The command works when the where module_ID='" & moduleSelect & "' statement is removed and I do not know how to fix this, can anyone help?
Dim moduleSelect As String = moduleRadio.SelectedValue
Using connection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Using avgCom As New SqlCommand("SELECT AVG(exam) FROM completed_module where module_ID='" & moduleSelect & "' ", _
connection)
connection.Open()
Dim avgObject As Integer = CInt(avgCom.ExecuteScalar())
Dim averageVar As String
averageVar = avgObject.ToString
avgLabel.Text = averageVar
End Using
I believe you are looking for something like this, first checking if it is dbnull:
Dim moduleSelect As String = moduleRadio.SelectedValue
Using connection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Using avgCom As New SqlCommand("SELECT AVG(exam) FROM completed_module where module_ID='" & moduleSelect & "' ", _
connection)
connection.Open()
Dim result = avgCom.ExecuteScalar()
If IsDBNull(result) then return
Dim avgObject As Integer = CInt(result)
Dim averageVar As String
averageVar = avgObject.ToString
avgLabel.Text = averageVar
End Using
DBNull means that the record in the database does not contain a value for the column. So basically you are trying to convert "nothing" into a number.
What do you want your program to do? Skip the row? Use a default value instead?
If the command really "works" if you remove a statement from the command, I suggest you simply remove it.
Use Convert.ToString instead. Directcast as string does not work for Null/Nothing
UPDATE
Problem happens whenever you do not receive any results.
I tested, so CStr to Convert.ToString works for DBNUll, but CInt and Convert.ToIntXX still throws an eception.
You can use
Dim scalarResult = avgCom.ExecuteScalar()
If Convert.IsDBNull(scalarResult) then
avgObject = 0
Else
avgObject = Convert.toInt32(scalarResult)
End If
Error :Conversion from type 'DBNull' to type 'Integer' is not valid.
This error Occurs because your query return a NULL value.. you can manage the NULL value by using the Below code..
Try like below it will help you...
connection.Open()
Dim result As String = avgCom.ExecuteScalar().ToString()
Dim avgObject As Integer = If(result = "", 0, CInt(result))
Probably this fails because there is a value missing. (i.e. NULL)
But it might work if you default to 0 if a row with NULL was encountered:
SELECT AVG(ISNULL(exam,0)) FROM completed_module where module_ID=
Otherwise make sure your table does not include NULL-values for that column:
UPDATE completed_module SET exam = 0 WHERE exam IS NULL
(maybe constraint it so it may not have future NULL-Values also ;))
EDIT: this assumes that you can actually have an average value for every row, even those where the column you access is NULL, in that case i would assume NULL does not add anything to your average value (which the other rows that share that ID might) so I default it to 0
I am currently using HDI Membership provider and the design looks as shown below:
Now I am trying to create a new user and insert those values into the database as shown below:
Try
Dim connectionString As String = "Data Source=.\sqlexpress;Initial Catalog=HDIMembershipProvider;Integrated Security=True"
Using cn As New SqlConnection(connectionString)
cn.Open()
Dim cmd As New SqlCommand()
cmd.CommandText = "INSERT INTO Users VALUES(#Username,#Password,#Email,#PasswordQuestion,#PasswordAnswer)"
Dim param1 As New SqlParameter()
param1.ParameterName = "#Username"
param1.Value = txtUsername.Text.Trim()
cmd.Parameters.Add(param1)
Dim param2 As New SqlParameter()
param2.ParameterName = "#Password"
param2.Value = txtPassword.Text.Trim()
cmd.Parameters.Add(param2)
Dim param3 As New SqlParameter()
param3.ParameterName = "#Email"
param3.Value = txtEmail.Text.Trim()
cmd.Parameters.Add(param3)
Dim param4 As New SqlParameter()
param4.ParameterName = "#PasswordQuestion"
param4.Value = txtSecurityQuestion.Text.Trim()
cmd.Parameters.Add(param4)
Dim param5 As New SqlParameter()
param5.ParameterName = "#PasswordAnswer"
param5.Value = txtSecurityAnswer.Text.Trim()
cmd.Parameters.Add(param5)
cmd.Connection = cn
cmd.ExecuteNonQuery()
cn.Close()
End Using
Successlbl.show
Successlbl.show.Text = "Regisration Success."
Catch
Errolbl.Show()
Errolbl.Text = "Your account was not created.Please try again."
End Try
Now the problem is the data is not inserting to the database. I would like to know If anyone can point me where I'm going wrong?
Your insert statement is incorrect - since you are not specifying any field names you should be supplying values for all columns.
The fix is to supply the names of the columns you are insert into.
The screenshot also shows that there is a required ApplicationName column, so unless it has a DEFAULT defined, you will need to supply that as well.
Assuming you have a DEFAULT defined on ApplicationName:
cmd.CommandText = "INSERT INTO Users ( Username, Password, Email, PasswordQuestion, PasswordAnswer) VALUES(#Username,#Password,#Email,#PasswordQuestion,#PasswordAnswer)"