I have a problem when i m connection with access database then i m getting a error Syntax error in INSERT INTO statement. and my code is :
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Geeta/Desktop/Database2.accdb;Persist Security Info=False;");
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string query = "insert into data (FirstName,Email,Password,Address) values ('" +
txt_fstname.Text + "','" + txt_email.Text + "', '" +
txt_pass.Text + "', '" + txt_add.Text + "')";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("Default.aspx");
plz suggest me.
"Thanks"
Password is a reserved word in Jet/ACE SQL so you must enclose it in square brackets:
string query = "insert into data (FirstName,Email,[Password],Address) values ('" +
Related
I am trying to insert data from vb.net into a SQL Server database.
My table :
CREATE TABLE [dbo].[gsb_dtab]
(
[gsb_sno] [int] IDENTITY(1,1) NOT NULL,
[gsb_date] [date] NOT NULL,
[gsb_quality] [nchar](20) NOT NULL,
[gsb_stype] [nchar](1) NOT NULL,
[gsb_taka] [int] NULL
)
VB.NET code:
cmd.CommandText = "INSERT INTO gsb_dtab (gsb_date, gsb_quality, gsb_taka)
VALUES('" + out_date + "','" + se_qcombo.Text + "','" + txt_taka.Text + "');"
The values I want to store are :
out_date = 2020-05-03
se_qcombo = Ranial
txt_taka = 48
but SQL Server throws an error:
Error converting data type varchar to numeric
The error happens in txt_taka insert; when I ignore txt_taka, then data is inserted successfully.
I am using SQL Server 2008 R2 and vb.net 2010
Please help - what can I do ?
Do not concatenate strings to build .CommandText. You will be open to sql injection and you .CommandText is much harder to read and maintain.
The Using...End Using block ensures that you connection and command are closed and disposed even it there is an error.
Private Sub InsertSomething(out_date As Date)
Dim sqlString = "INSERT INTO gsb_dtab (gsb_date, gsb_quality, gsb_taka)
VALUES(#Date, #seq, #taka);"
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand(sqlString, cn)
cmd.Parameters.Add("#Date", SqlDbType.Date).Value = out_date
cmd.Parameters.Add("#seq", SqlDbType.NVarChar, 20).Value = se_qcombo.Text
cmd.Parameters.Add("#taka", SqlDbType.Int).Value = CInt(txt_taka.Text)
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
Put strings in apostrophes, but don't do it with numbers. The format of date values should be "'yyyy-MM-dd'" or 'yyyy-MM-dd HH:mm:ss'. Also use "&" for string concatenation, because "+" could lead to weird errors. And the semicolon at the end isn't needed. So the code could look like:
Dim SQL As String = "INSERT INTO gsb_dtab (gsb_date, gsb_quality, gsb_taka) " &
"VALUES(" & Strings.Format(out_date, "\'yyyy-MM-dd\'") &
", '" & se_qcombo.Text & "', " & txt_taka.Text & ")"
cmd.CommandText = SQL
Please use below code.
cmd.CommandText = "INSERT INTO gsb_dtab (gsb_date, gsb_quality, gsb_taka)
VALUES('" + out_date + "','" + se_qcombo.Text + "','" + Convert.toInt32(txt_taka.Text) + "');"
you need to convert the int value.
I'm trying to update a SQL Server table (connected to a WPF project) and I'm getting the message
Incorrect syntax near the keyword WHERE
What is wrong in my code?
private void Save_button_Click(object sender, RoutedEventArgs e)
{
try
{
Select("INSERT INTO [dbo].[Users](sumScore, doneLevels) VALUES ('" + ClsGlobal.sumScore + "','" + ClsGlobal.DoneLevels + "') WHERE [userName]= '" + ClsGlobal.userName + "'");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public DataTable Select(string selectSQL)
{
DataTable dataTable = new DataTable("dataBase");
SqlConnection sqlConnection = new SqlConnection(#"Data Source =(LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\Avraham\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB\New Database.mdf ");
sqlConnection.Open();
SqlCommand sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandText = selectSQL;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
I'd try to get [and] or (and) near the word username, but this still didn't work.
This query:
INSERT INTO [dbo].Users
VALUES ('" + ClsGlobal.sumScore + "','" + ClsGlobal.DoneLevels + "')
WHERE [userName]= '" + ClsGlobal.userName;
Does not make sense. INSERT inserts new rows, so WHERE is not appropriate.
Perhaps you want an UPDATE:
UPDATE dbo.Users
SET sumScore = ?,
DoneLevels = ?
WHERE userName = ?;
You should be passing in ClsGlobal.sumScore, ClsGlobal.DoneLevels, and ClsGlobal.userName as parameters rather than munging the query string.
I want some sort of label that is counting every record that is imported in the database.
Do I need to use a for each loop?
Can someone explain me how to do it, or set me on the right way to do it?
With cmd
.CommandText = "INSERT INTO Workflow ([Import], [DossierPad]) VALUES ('" + Import + "','" + Pad + "')"
.ExecuteNonQuery()
.CommandText = "INSERT INTO Data ([DossierPad], [Tif], [Grootte]) VALUES ('" + Pad + "','" + stukjes(0) + "','" + stukjes(2) + "')"
.ExecuteNonQuery()
If Tifcheck(Tif) = False Then
cmd.CommandText = "Update Data Set Tif = '" & Tif & "' WHERE Tif="
ElseIf Tifcheck(Tif) = True Then
End If
If stukjes(2) < 20000 Then
.CommandText = "UPDATE Data SET Blanco = '" & blanco & "' WHERE DossierPad = '" & Pad & "'"
.ExecuteNonQuery()
Else
.CommandText = "UPDATE Data SET Blanco = '" & blanco1 & "' WHERE DossierPad = '" & Pad & "'"
.ExecuteNonQuery()
End If
End With
This is the part of code where I insert records in my database.
Now my question is how can I get a label to count every record in the database while it is intering.
As specified in the MSDN docs, the method ExecuteNonQuery() returns the number of rows affected by your query. This is often used to check that your insert query ended up correctly.
So what you can do is declare an Integer somewhere in your code, and increment this integer with the result of the ExecuteNonQuery() method call.
At the end, you can update a Label with the value of your integer.
Some code:
'At the beginning of your update function
Dim myCounter As Integer
'...
'Whenever you run ExecuteNonQuery() on an INSERT statement
myCounter += .ExecuteNonQuery()
'...
'Finally, on the label that should display the result
myLabel.Text = "Updated " & myCounter.toString() & " rows."
this is the code I am using for trying to insert a row to my dataset.
It executes properly till sqlConnection is opened. But the nonQuery execution throws a 'System.Data.SqlClient.SqlException' I believe there is something wrong with my connection string, I copied it from the app./config file and I cannot figure out what is wrong. Also, I know I should use a parameterized SQL query, I will implement that later.
Dim sqlConnection1 As New System.Data.SqlClient.SqlConnection("Data Source=(localdb)\MSSQLLocalD;Initial Catalog=ContactInfo;Integrated Security=True;Pooling=False")
Dim cmd As New SqlClient.SqlCommand
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO Table (ID, FirstName, MiddleName, LastName, Type, Telephone, Extension, Email) VALUES (" + row.ID.ToString + "," + "'" + row.FirstName + "'" + "," + "'" + row.MiddleName + "'" + "," + "'" + row.LastName + "'" + "," + "'" + row.Type + "'" + "," + row.Telephone.ToString + "," + "'" + row.Extension + "'" + "," + "'" + row.Email + "')"
cmd.Connection = sqlConnection1
sqlConnection1.Open()
cmd.ExecuteNonQuery()
sqlConnection1.Close()
First, Don't think that you can name your table "Table" so change it to your real table name and it should run
And USE SQL PARAMETERS!
Second, get the result of ExecuteNonQuery to a variable so you can check, if a record was written or not.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# stored procedure with parameters
I am trying to call a stored procedure from c# passing in multiple parameters and can't to get it working. Here is what I have so far.
cmd = new SqlCommand();
cmd = dbConn.CreateCommand();
cmd.CommandText = "inserttoTable #size = " + size + ", #brand = " + brand + ", #manu = " + manu + ", #t= " + id.ToString();
cmd.ExecuteNonQuery();
Size, brand and manu are all strings. inserttoTable is the stored procedure.
I get the following error : System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'TO'.
check out this:
SqlCommand.Parameters Property
You'll have fewer problems if you use parameters and change the command type to stored procedure:
cmd = new SqlCommand();
cmd = dbConn.CreateCommand();
cmd.CommandText = "inserttoTable";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#size", size));
cmd.Parameters.Add(new SqlParameter("#brand", brand));
cmd.Parameters.Add(new SqlParameter("#manu", manu));
cmd.Parameters.Add(new SqlParameter("#t", id.ToString()));
cmd.ExecuteNonQuery();
Although this is not the best method to call a stored procedure, if you add single quotes around the string parameters, you should be fine.
cmd = new SqlCommand();
cmd = dbConn.CreateCommand();
cmd.CommandText = "inserttoTable #size = '" + size + "', #brand = '" + brand + "', #manu = '" + manu + "', #t= '" + id.ToString() + "'";
cmd.ExecuteNonQuery();
This code is very dated and was already deprecated 10 years ago.