Incorrect Syntax near ' '.C# - c#

I get error
INCORRECT SYNTAX NEAR ' '
Here is my code:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection=conn;
cmd.CommandText = "update student set Name='" + textBox1.Text + "',Family='" + textBox2.Text + "',Fathername='" + textBox3.Text + "',ShenasName='" + textBox4.Text + "',CodeMeli'" + textBox5.Text + "',Tavalod'" + maskedTextBox1.Text + "',Address'" + richTextBox1.Text + "',Madraak'" + textBox7.Text + "',Shahriye'" + textBox8.Text + "',Mobile'" + textBox6.Text + "'where Name=" + textBox1.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
My database is SQL Server Express.

There are some errors:
missing equals after: CodeMeli=, Tavalod=, Address=, Madraak=, Shahriye=, Mobile=
missing ending of the sql statement + "'"
This will work:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = "update student set Name='" + textBox1.Text + "',Family='" + textBox2.Text + "',Fathername='" + textBox3.Text + "',ShenasName='" + textBox4.Text + "',CodeMeli='" + textBox5.Text + "',Tavalod='" + maskedTextBox1.Text + "',Address='" + richTextBox1.Text + "',Madraak='" + textBox7.Text + "',Shahriye='" + textBox8.Text + "',Mobile='" + textBox6.Text + "'where Name='" + textBox1.Text + "'";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
In any case, I recommend you the use of Parameters. Why?
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd= new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = #"UPDATE Student SET Name=#Name, Family=#Family, Fathername=#Fathername, ShenasName=#ShenasName, CodeMeli = #CodeMeli,Tavalod=#Tavalod, Address=#Address, Madraak=#Madraak, Shahriye=#Madraak, Mobile=#Mobile WHERE Name=#Name";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Family", textBox2.Text);
cmd.Parameters.AddWithValue("#Fathername", textBox3.Text);
cmd.Parameters.AddWithValue("#ShenasName", textBox4.Text);
cmd.Parameters.AddWithValue("#CodeMeli", textBox5.Text);
cmd.Parameters.AddWithValue("#Tavalod", maskedTextBox1.Text);
cmd.Parameters.AddWithValue("#Address", richTextBox1.Text);
cmd.Parameters.AddWithValue("#Madraak", textBox7.Text);
cmd.Parameters.AddWithValue("#Shahriye", textBox8.Text);
cmd.Parameters.AddWithValue("#Mobile", textBox6.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
using table2 instead of student
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = "update table2 set Name='" + textBox1.Text + "',Family='" + textBox2.Text + "',Fathername='" + textBox3.Text + "',ShenasName='" + textBox4.Text + "',CodeMeli='" + textBox5.Text + "',Tavalod='" + maskedTextBox1.Text + "',Address='" + richTextBox1.Text + "',Madraak='" + textBox7.Text + "',Shahriye='" + textBox8.Text + "',Mobile='" + textBox6.Text + "'where Name='" + textBox1.Text + "'";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
OR
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd= new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = #"UPDATE table2 SET Name=#Name, Family=#Family, Fathername=#Fathername, ShenasName=#ShenasName, CodeMeli = #CodeMeli,Tavalod=#Tavalod, Address=#Address, Madraak=#Madraak, Shahriye=#Madraak, Mobile=#Mobile WHERE Name=#Name";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Family", textBox2.Text);
cmd.Parameters.AddWithValue("#Fathername", textBox3.Text);
cmd.Parameters.AddWithValue("#ShenasName", textBox4.Text);
cmd.Parameters.AddWithValue("#CodeMeli", textBox5.Text);
cmd.Parameters.AddWithValue("#Tavalod", maskedTextBox1.Text);
cmd.Parameters.AddWithValue("#Address", richTextBox1.Text);
cmd.Parameters.AddWithValue("#Madraak", textBox7.Text);
cmd.Parameters.AddWithValue("#Shahriye", textBox8.Text);
cmd.Parameters.AddWithValue("#Mobile", textBox6.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");

SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection=conn;
cmd.CommandText = #"
UPDATE
Student
SET
Name=#Name, Family=#Family, Fathername=#Fathername, ShenasName=#ShenasName, CodeMeli = #CodeMeli,
Tavalod=#Tavalod, Address=#Address, Madraak=#Madraak, Shahriye=#Madraak, Mobile=#Mobile
WHERE
Name=#Name";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Family", textBox2.Text);
cmd.Parameters.AddWithValue("#Fathername", textBox3.Text);
cmd.Parameters.AddWithValue("#ShenasName", textBox4.Text);
cmd.Parameters.AddWithValue("#CodeMeli", textBox5.Text);
cmd.Parameters.AddWithValue("#Tavalod", maskedTextBox1.Text);
cmd.Parameters.AddWithValue("#Address", richTextBox1.Text);
cmd.Parameters.AddWithValue("#Madraak", textBox7.Text);
cmd.Parameters.AddWithValue("#Shahriye", textBox8.Text);
cmd.Parameters.AddWithValue("#Mobile", textBox6.Text);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
Here is the code. First Format your query properly, your query was unreadable. Second use Command parameters to avoid SQL Injection. You can read in Wikipedia about sql injection. Third write "nice" textBox ID, which have some meaning.

Look at your CommandText. There are some Parameters without ( = )
Format like this :
cmd.CommandText = "update student set Name='" + textBox1.Text + "',
Family='" + textBox2.Text + "',
Fathername='" + textBox3.Text + "',
ShenasName='" + textBox4.Text + "',
CodeMeli='" + textBox5.Text + "',
Tavalod='" + maskedTextBox1.Text + "',
Address='" + richTextBox1.Text + "',
Madraak='" + textBox7.Text + "',
Shahriye='" + textBox8.Text + "',
Mobile='" + textBox6.Text + "'
where Name=" + textBox1.Text;

Incorrect syntax ')'
private void btnInsert_Click(object sender, EventArgs e) {
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("INSERT INTO Customers(Id,Name,Country,) values (#Id,#Name,#Country)",con);
con.Open();
cmd.Parameters.AddWithValue("#Id",dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Name",dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Country",dataGridView1.Rows[i].Cells[2].Value);
cmd.ExecuteNonQuery();
con.Close();
}
MessageBox.Show("Added successfully!");
}

Related

'ExecuteNonQuery: Connection property has not been initialized.'

I have searched this forum, and have tried a multitude of possible solutions I found, but nothing is working. can anyone shed some light on this situation? Thanks!
SqlConnection con = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(
"INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID) " +
"VALUES ('" + GenName.Text + "' , '" + GenAdd.Text + "' , '" + GenCity.Text + "' , '" + GenState.Text + "' , '" + GenZip.Text + "' , '" + GenPhone.Text + "' ," +
" '" + GenContact.Text + "' , '" + GenEPAID.Text + "' ), con");
cmd.ExecuteNonQuery();
con.Close();
It looks like when you are creating your SqlCommand, you have the connection as part of the Insert statement. Specifically, ", con" is still wrapped inside your text string. If you move your last double quote to after the parenthesis, it should work.
However, I would suggest rewriting your code like this:
using (var con = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True"))
{
if(ConnectionState.Closed == con.State) con.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = $#"INSERT INTO tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)
VALUES ('{GenName.Text}', '{GenAdd.Text}', '{GenCity.Text}', '{GenState.Text}', '{GenZip.Text}', '{GenPhone.Text}', '{GenContact.Text}', '{GenEPAID.Text}')";
cmd.ExecuteNonQuery();
}
}
This is the code that I ended up using. Thanks everyone for your help.
SqlConnection myConnection =
new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
SqlCommand myCommand = new SqlCommand(
"INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)" +
"VALUES (#GenName, #GenAdd, #GenCity, #GenState, #GenZip, #GenPhone, #GenContact, #GenEPAID)");
myCommand.Parameters.AddWithValue("#GenName", GenName.Text);
myCommand.Parameters.AddWithValue("#GenAdd", GenAdd.Text);
myCommand.Parameters.AddWithValue("#GenCity", GenCity.Text);
myCommand.Parameters.AddWithValue("#GenState", GenState.Text);
myCommand.Parameters.AddWithValue("#GenZip", GenZip.Text);
myCommand.Parameters.AddWithValue("#GenPhone", GenPhone.Text);
myCommand.Parameters.AddWithValue("#GenContact", GenContact.Text);
myCommand.Parameters.AddWithValue("#GenEPAID", GenEPAID.Text);
myConnection.Open();
myCommand.Connection = myConnection;
MessageBox.Show("You Have Successfully Added a New Generator To SQL");
myCommand.ExecuteNonQuery();
myConnection.Close();

How can I add some values into my database

I'm a beginner in C# and I wrote a code that connect to my database but It give me a error
I did everything from first but nothing happened
private void btnSubmit_Click(object sender, EventArgs e)
{
string conString = "data source=DESKTOP-D5VFL9P; initial catalog = university; integrated security = True; MultipleActiveResultSets = True;";
using (SqlConnection connection = new SqlConnection(conString))
{
connection.Open();
using(SqlCommand command = new SqlCommand("INSERT INTO Persons (PersonID, LastName, FirstName, Age, City) VALUES (" + int.Parse(txtPersonID.Text) + ", '" +
txtLastName.Text + "', '" + txtFirstName.Text + "' ," + int.Parse(txtAge.Text) + ", '" + txtCity.Text + "'", connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
MessageBox.Show("Data inserted");
txtFirstName.Text = "";
txtLastName.Text = "";
txtPersonID.Text = "";
txtAge.Text = "";
txtCity.Text = "";
}
}
}
}
I want to add some values to my database
There should be a ) behind the City. Like txtCity.Text + "')".
I am not recommending this as it is definitely opens a door for SQL Injection Attack but Use below string that will work in your case:
string cmdText = "INSERT INTO Persons(PersonID,LastName,FirstName,Age,City)" +
" VALUES ('" + int.Parse(txtPersonID.Text) + "', " +
"'" + txtLastName.Text + "', " +
"'" + txtFirstName.Text + "' ,'" +
int.Parse(txtAge.Text) + "', '" +
txtCity.Text + "')"
I would do something like this:
using (SqlConnection conn = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"INSERT INTO Persons (PersonID,LastName,FirstName,Age,City) VALUES (#PersonID,#LastName,#FirstName,#Age,#City)";
cmd.Parameters.AddWithValue("#PersonID", int.Parse(txtPersonID.Text));
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
cmd.Parameters.AddWithValue("#City", txtCity.Text);
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
if(rowsAffected > 0)
{
MessageBox.Show("Data inserted");
}
else
{
MessageBox.Show("Failed");
}
conn.Close();
}

Unsupported exception in c# inserting values

I'm probably blind or sm.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Szymek\Desktop\Komunikator\Komunikator\Baza.mdf;Integrated Security=True");
private void button1_Click(object sender, EventArgs e)
{
con.Open();
String query = " INSERT INTO Uzytkownicy (imie, nazwisko, e-mail,login, haslo) VALUES ('"+ textBox1.Text + "','" +textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
con.Close();
MessageBox.Show(" Zapisano ! ");
this.Hide();
Login move = new Login();
move.ShowDialog();
}
Error at query I think:
System.Data.SqlClient.SqlException: „Incorrect syntax near '-'.”

Syntax error near table_name

So I have this code to insert values from text-box into my database, but every time i execute my code and enters my data i get this message
"Syntax Error near keyword user"
string Connectionstring = #"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Bank_System.mdf;Integrated Security=True; User Instance=True";
SqlConnection cnn = new SqlConnection(Connectionstring);
cnn.Open();
SqlCommand cmd1 = new SqlCommand("insert into user values('" + int.Parse(textBox1.Text) + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + int.Parse(textBox6.Text) + "')", cnn);
SqlDataReader dr1 = cmd1.ExecuteReader();
dr1.Close();
MessageBox.Show(" Record inserted ", " information inserted");
cnn.Close();
USER is a reserved keyword in T-SQL. You should use it with square brackets like [USER]. However, the best solution is to change the name to a non-reserved word.
But more important, please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
By the way, I don't understand why you used ExecuteReader for an INSERT command. Looks like you just need to use ExecuteNonQuery instead.
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command.
Also use using statement to dispose your SqlConnection, SqlCommand.
using(SqlConnection cnn = new SqlConnection(Connectionstring))
using(SqlCommand cmd1 = cnn.CreateCommand())
{
cmd1.CommandText = "INSERT INTO [USER] VALUE(#p1, #p2, #p3, #p4, #p5, #p6)";
cmd1.Parameters.AddWithValue("#p1", int.Parse(textBox1.Text));
cmd1.Parameters.AddWithValue("#p2", textBox2.Text);
cmd1.Parameters.AddWithValue("#p3", textBox3.Text);
cmd1.Parameters.AddWithValue("#p4", textBox4.Text);
cmd1.Parameters.AddWithValue("#p5", textBox5.Text);
cmd1.Parameters.AddWithValue("#p6", int.Parse(textBox6.Text));
cnn.Open();
int count = cmd1.ExecuteNonQuery();
if(count > 0)
MessageBox.Show("Record inserted");
}
You try to concatenate int to string. The error is here: int.Parse(textBox1.Text) -> you need to convert to string after you test if is integer.
Try this for test : int.Parse(textBox1.Text).ToString() to see if this is your problem.
You try gather string to an integer by using:
"insert into user values('" + int.Parse(textBox1.Text) ....
=> string + int
Correct is:
SqlCommand cmd1 = new SqlCommand("insert into user values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "')", cnn);
try to validate if textBox1.Text and textBox6.Text before concatenate but is recommended to use parameters.

UPDATE STATEMENT in asp.net using c#

i am using asp.net with C# as code behind
OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False");
cn.Open();
string sql = "UPDATE main SET s_name='"+TextBox1.Text+"',inst_code='"+DropDownList1.SelectedItem+"',ms_oms='"+Label7.Text+"',elligiblity='"+Label12.Text+"',Board='"+DropDownList5.SelectedItem+"',percentage='"+TextBox4.Text+"' WHERE elg_id = '"+DropDownList4.SelectedItem+"'";
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
Response.Write("alert('DATA UPDATED')");
i am getting error on
cmd.ExecuteNonQuery();
that Data type mismatch in criteria expression.
Don't code like
string connection_string="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False";
using(OleDbConnection cn = new OleDbConnection(connection_string))
{
cn.Open();
string sql = "UPDATE main SET s_name=?,inst_code=?,ms_oms=?,elligiblity=?,Board=?,percentage=?,amount=? WHERE elg_id =?";
using(OleDbCommand cmd = new OleDbCommand(sql, cn))
{
cmd.Parameters.Add(new OleDbParameter("s_name",TextBox1.Text.Trim()));
cmd.Parameters.Add(new OleDbParameter("inst_code",DropDownList1.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter("ms_oms",Label7.Text.ToString()));
cmd.Parameters.Add(new OleDbParameter("elligiblity",Label12.Text));
cmd.Parameters.Add(new OleDbParameter("Board",DropDownList5.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter("percentage",DropDownList5.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter(amount",DropDownList5.SelectedItem.Value.ToString()));
cmd.Parameters.Add(new OleDbParameter("elg_id",DropDownList5.SelectedItem.Value.ToString()));
cmd.ExecuteNonQuery();
cn.Close();
}
}
Response.Write("alert('DATA UPDATED')");
Remove single quotes around DropDownList4.SelectedItem. I bet your elg_id column is of type integer or something, and you're giving it a string.
Having that said, you would be really better off if you provided text of error, database table structure and maybe some other information so that people wouldn't have to read your mind.
Can you try DropDownList1.SelectedItem.Text or DropDownList1.SelectedItem.Value
This should be the same for all DropDownLists.
Also you might have to convert TextBox4 to the appropriate datatype for "percentage".
Assuming that the percentage is a Double, you'd need something like
Double.Parse(Textbox4.Text)
Lastly, if you're not sending a "string" to the query, you would be really good to remove the single quotes from those fields. That way you're not parsing the data but still sending string information.
this is de correct code
OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False");
cn.Open();
string sql = "UPDATE main SET s_name='" + TextBox1.Text + "',inst_code='" + DropDownList1.SelectedItem.Value.ToString() + "',ms_oms='" + Label7.Text + "',elligiblity='" + Label12.Text + "',Board='" + DropDownList5.SelectedItem.Value.ToString() + "',percentage='" + float.Parse(TextBox4.Text) + "',amount='" + Label10.Text + "' WHERE elg_id = " + DropDownList4.SelectedItem.Value + "";
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
Response.Write("alert('DATA UPDATED')");
thanxx
OleDbConnection cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Documents and Settings\CJP\My Documents\Visual Studio 2005\WebSites\NewElligibleSoft\elligiblity.mdb;Persist Security Info=False");
cn.Open();
string sql = "UPDATE main SET s_name='" + TextBox1.Text + "',inst_code='" + DropDownList1.SelectedItem.Value.ToString() + "',ms_oms='" + Label7.Text + "',elligiblity='" + Label12.Text + "',Board='" + DropDownList5.SelectedItem.Value.ToString() + "',percentage='" + float.Parse(TextBox4.Text) + "',amount='" + Label10.Text + "' WHERE elg_id = " + DropDownList4.SelectedItem.Value + "";
OleDbCommand cmd = new OleDbCommand(sql, cn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
Response.Write("alert('DATA UPDATED')");

Categories

Resources