Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I get an error on sc.ExecuteNonQuery();.. Error: Incorrect syntax near 's'
Code:
con = new SqlConnection("Data Source=DELL-PC;Initial Catalog=sashi;Integrated Security=True");
con.Open();
SqlCommand sc = new SqlCommand("INSERT INTO Login VALUES('" + textBoxUID.Text + "','" + textBoxPWD.Text + "','" + comboBoxQUN.Text + "','" + textBoxANS.Text + "' ) ", con);
sc.ExecuteNonQuery();
MessageBox.Show("Record has been inserted");
con.Close();
What I forgot or where is the error?
Please Use Parameters like this:
using (var con = new SqlConnection("Data Source=DELL-PC;Initial Catalog=sashi;Integrated Security=True"))
{
con.Open();
using(var sc = connection.CreateCommand())
{
sc.CommandText = "INSERT INTO Login VALUES(#uid,#pass,#qun,#ans)";
sc.Parameters.Add(new SqlParameter("#uid", textBoxUID.Text));
sc.Parameters.Add(new SqlParameter("#pass", textBoxPWD.Text));
sc.Parameters.Add(new SqlParameter("#qun", comboBoxQUN.Text));
sc.Parameters.Add(new SqlParameter("#ans", textBoxANS.Text));;
sc.ExecuteNonQuery();
}
}
Sql parameters helps prevent SQL Injection attacks.. and ist easier to read..
Does your login table have only four columns? otherwise you must also specify this in your insert-statement: INSERT INTO (col1, col2 ....
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Im trying to retrieve no of rows from sql based user input & display in gridview
Please help!
Int32 text = Convert.ToInt32(this.Txtusers.Text);
con.Open();
cmd = new SqlCommand("select TOP '" + text + "' * from Avaya_Id where LOB = '" + DDLOB.SelectedItem.Value + "' and Status = 'Unassigned'", con);
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
con.Close();
Here is how it should be written.
int text;
if(int.TryParse(this.Txtusers.Text, out text)
{
using(var con = new SqlConnection(connectionString)
{
using(var cmd = new SqlCommand("select TOP (#top) * from Avaya_Id where LOB = #LOB and Status = 'Unassigned'", con))
{
cmd.Parameters.Add("#top", SqlDbType.Int).Value = text;
cmd.Parameters.Add("#LOB", SqlDbType.Int).Value = DDLOB.SelectedItem.Value;
con.Open();
using(var rdr = cmd.ExecuteReader())
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
}
Points of interest:
Using parameters to avoid the risk of Sql Injection.
Changed Convert.ToInt32 to int.TryParse. Never trust user input.
Use the using statement for every instance that implements the IDisposable interface.
Please note that using top x without an order by clause means you get x arbitrary records from the database - since database tables are unordered by nature and the only way to ensure the order of the rows returned from a select statement is to use the order by clause.
Please note I've guessed that the second parameter is an int, if it's not, change the data type.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am relatively new to c# and I am practicing adding databases to store my information. I cannot get the connection string to work for me. the code is :
SqlConnection con = new SqlConnection("Data Source = (LocalDB)/MSSQLLocalDB; AttachDbFilename='C:/Users/joeco_000/Documents/Visual Studio 2015/Projects/Telephone project/Telephone project/Database1.mdf';Integrated Security = True'");
I then have a button that will add the information to the database that is:
private void button2_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand(#" INSERT INTO Phon table (First,last,email,mobile,catagory) VALUES ('" + textBox2.Text + "' , '" + textBox3.Text + "' , '" + textBox4.Text + "' , '" + textBox5.Text + "','" + comboBox1.Text + "')");
cmd.ExecuteNonQuery();
con.Close();
I have taken this information from a tutorial that is 6 years old. Any help would be amazing.
You haven't associated the command with the connection before attempting to execute the query. One way to do this is:
SqlCommand cmd = new SqlCommand(sql, connection)
Another way is:
cmd.Connection = con;
The name Phon table is not a valid table name. If your table really has a space in its name you need to surround it with square braces
INSERT INTO [Phon table] (First,last,email.......
Note that this is in addition to associating your command with your connection as the other answer indicates.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
i have database contain column name Code data type nvarchar(50) i connected to my database by c# and created a SQL command as
string code = "e01";
SqlCommand command = new SqlCommand("select * from inv where code = " + code + ";", conn);
SqlDataReader reader = command.ExecuteReader();
i found an error says
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid column name 'e01'.
and if i but number instead of e01 it work fine ..
your are missing quotes. Try this:
string code = "e01"
SqlCommand command = new SqlCommand("select * from inv where code = '" + code + "';", conn);
SqlDataReader reader = command.ExecuteReader();
Also, it's recomended use parameters instead concatenating values. This avoid sql injection attacks or sql errors if your code contains special characters, like quotes:
SqlCommand command = new SqlCommand("select * from inv where code = #pCode", conn);
command.Parameters.Add(new SqlParameter("#pCode", code));
SqlDataReader reader = command.ExecuteReader();
You forgot to put quotes around your column value, because e01 is a value and not a column it needs to be surrounded by single quotes.
SqlCommand command = new SqlCommand("select * from inv where code = '" + code + "';", conn);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Why does this code throw an error?
using (MySqlConnection cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
{
{
MySqlCommand Command = new MySqlCommand();
Command.Connection = cn;
Command.CommandText = "UPDATE TeleworksStats SET Ja= ('" + JaTak +
"') WHERE Brugernavn = " + VarribleKeeper.Brugernavn + "' AND Dato = " +
DateTime.Today.ToString("yyyy-MM-dd") + "";
cn.Open();
Command.ExecuteNonQuery();
//Ryd op
Command.Dispose();
cn.Close();
}
}
Rather than just forgetting ' for the value of Brugernavn column and both single quotes for Dato column, I think you have more things to keep in mind.
Use using statement to dispose your Command object as you did for your connection instead of calling Close or Dispose methods manually.
Use paramterized queries instead of string concatenation. This kind of codes are open for SQL Injection attacks.
Looks like you try to save your DateTime values with their string representations. Do not do that! If you wanna keep your DateTime values to your database, you need to pass them directly. Change your Dato column to DateTime type. Read: Bad habits to kick : choosing the wrong data type
using(var cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
using(var Command = cn.CreateCommand())
{
Command.CommandText = #"UPDATE TeleworksStats SET Ja = #Ja
WHERE Brugernavn = #Brugernavn AND Dato = #Dato";
Command.Parameters.Add("#Ja", MySqlDbType.VarChar).Value = JaTak;
Command.Parameters.Add("#Ja", MySqlDbType.VarChar).Value = VarribleKeeper.Brugernavn;
Command.Parameters.Add("#Ja", MySqlDbType.DateTime).Value = DateTime.Today;
// I assumed your column types. You should write proper column types instead.
cn.Open();
Command.ExecuteNonQuery();
}
You missed one quote ' after Brugernavn = and Dato:
Brugernavn = "... '" + VarribleKeeper.Brugernavn + "' AND Dato = '" +
DateTime.Today.ToString("yyyy-MM-dd") + "'";
Also I strongly recommend that you always use parameterized queries to avoid SQL Injection like this:
Command.CommandText =
"UPDATE TeleworksStats SET Ja = #Ja WHERE Brugernavn = #Brugernavn and ...";
Command.Parameters.AddWithValue("#Ja", JaTak);
Command.Parameters.AddWithValue("#Brugernavn", VarribleKeeper.Brugernavn);
Although specify the type directly and use the Value property is more better than AddWithValue. Check this: Can we stop using AddWithValue() already?
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkUser = " select count(*) form Userdata where Username='" + TextBoxUN.Text + "' ";
SqlCommand cmd = new SqlCommand(checkUser,conn);
if (temp==1)
{
Response.Write("User Already Exists");
}
conn.Close();
System.Data.SqlClient.SqlException was unhandled by user code
HResult=-2146232060 Message=Incorrect syntax near 'Userdata'
int temp= Convert.ToInt32(cmd.ExecuteScalar().ToString());
The error message says:
Incorrect syntax near 'Userdata'
That tells you that the SQL parser gave up at the word Userdata because the syntax no longer made sense, which usually means that the actual error is close before that word.
If you look at that part of your query:
select count(*) form Userdata
The word right before Userdata is form, but you should recognise that it's not the keyword from that you intended to write.
Side note (but an important one): The value that you concatentate into the query is not properly escaped, so the code is wide open to SQL injection attacks. You should use a parameter to put the value in the query:
string checkUser = "select count(*) from Userdata where Username = #Username";
SqlCommand cmd = new SqlCommand(checkUser,conn);
cmd.Parameters.AddWithValue("#Username", TextBoxUN.Text);