This question already has answers here:
Why do we always prefer using parameters in SQL statements?
(7 answers)
How to give ADO.NET Parameters
(4 answers)
Closed 5 months ago.
I am trying to add values to a database using WPF form.
This is my code:
private void Insertbtn_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=DESKTOP-HSIK0SQ; Initial Catalog=Demo; Integrated Security=SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Student VALUES ("+ RollNumebrtxt + "," + FNametxt + "," + Coursetxt + ")";
int count = cmd.ExecuteNonQuery();
MessageBox.Show(count + " record saved successfully");
conn.Close();
}
When I am hitting the insert button:
This is the exception being thrown:
I am sure that whichever the labels and text boxes I have added they have unique name in the property. It is throwing exception while executing the query command
I am not sure what I could miss here?
Make sure to surround these values with single quotes '', and if these variables are the TextBoxes, then you have to call .Text on them to get the proper values..
cmd.CommandText = "Insert into Student values ('"+ RollNumebrtxt.Text + "','" + FNametxt.Text + "','" +
Coursetxt.Text + "');";
Better to parametrised your query..
Replace
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Student VALUES ("+ RollNumebrtxt + "," + FNametxt + "," + Coursetxt + ")";
With
SqlCommand cmd = new SqlCommand("INSERT INTO Student VALUES(#RollNumber, #FName, #CourseName)", conn);
cmd.Parameters.Add("#RollNumber", SqlDbType.Int).Value = int.Parse(RollNumebrtxt.Text);
cmd.Parameters.Add("#FName", SqlDbType.VarChar, 100).Value = FNametxt.Text;
cmd.Parameters.Add("#CourseName", SqlDbType.VarChar, 100).Value = Coursetxt.Text;
Related
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.
public void showdata(string pss, string cipherText)
{
SqlConnection conn1 = new SqlConnection(str);
SqlCommand cmd1 = new SqlCommand("update Tbl_Users set Password = '" + pss + "'where Password ='" + cipherText + "'", conn1);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
sda1.Fill(ds1, "Tbl_Users");
dataGridView1.DataSource = ds1;
dataGridView1.DataMember = ds1.Tables["Tbl_Users"].ToString();
}
Ur Updated Ans
public void showdata(string pss, string cipherText)
{
SqlConnection conn1 = new SqlConnection(str);
> SqlCommand cmd1 = new SqlCommand("**update Tbl_Users set Password = '" +
> pss + "'where Password ='" + cipherText + "'"**, conn1);
It should be select statment not Update Or Inser Statment
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
Datatable ds1 = new Datatable ();
sda1.Fill(ds1);
dataGridView1.DataSource = ds1;
}
I have the following code
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtFileLocation.Text;
using (DbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
DbCommand command = conn.CreateCommand();
string idfield = txtIDField.Text;
string picfield = txtPictureField.Text;
command.CommandText = "select " + idfield + ", " + picfield + " from " + selectedTable;
command.CommandType = CommandType.Text;
DbDataReader reader = command.ExecuteReader();
gridResults.DataSource = reader;
conn.Close();
}
The database is an access database as u might have seen from the connection string, also the database I was provided with store their images in the database, as Image attachment.
Whenever I load the grid it shows random stuff :(
eg.
I am not familiar with the wiring up of a database so this might be an easy question, how do I enable my picture list in my form?
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.
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 ('" +