This had to be a simple, ordinary SQL insert method but when I run it and I click "button1" I get the error
An unhandled exception of type 'system.data.sqlclient.sqlexception' occurred in system.data.dll
Does anyone know what the problem is?
namespace InsertDeleteUpdate_Login
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\C #\InsertDeleteUpdate-Login\InsertDeleteUpdate-Login\Database1.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
cmd.Connection = cn;
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "")
{
cn.Open();
cmd.CommandText = "INSERT INTO info (ID,Name,Password)" + " VALUES ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')'";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Inserare reusita");
cn.Close();
}
}
}
}
The root cause of your problem is that you are not using parameterized queries and are trying to create an sql string on the fly. As a result you make an error in the assembling code of that string. But if you use a parameterized query the chance of running into an issue like that is a lot lower because you don't have to mess about with quotes and the like. On top of this, you cannot have a sql injection attack if you use parameters and it makes the code more readable too.
Read http://www.dotnetperls.com/sqlparameter on how to use a parameterized query the way it should be done and don't just fix the textual error in the querystring. It is not the way it is supposed to be done.
This is a good explanation too : http://www.dreamincode.net/forums/topic/268104-parameterizing-your-sql-queries-the-right-way-to-query-a-database/
I can't add comments yet, but it looks like you might have an extra single quote after the last close bracket that shouldn't be there.
As mentioned by several people above, you should ALWAYS parameterise your queries, and you also have a trailing single quote, which is most likely what SQL Server is choking on.
Try something like this:
cmd.CommandText = "INSERT INTO info (ID, Name, Password) VALUES (#ID, #Name, #Password)";
cmd.Parameters.AddWithValue("#ID", textBox1.Text);
cmd.Parameters.AddWithValue("#Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Password", textBox3.Text);
cmd.ExecuteNonQuery();
Related
This is my first time creating a web api from scratch and I'm trying to get a selected value in a drop down bow to trigger an sql search and make the appropriate item appear in a text box. below is the relevant code
protected void btnRetrieve_Click(object sender, EventArgs e)
{
try
{
string pNameTemp = DropDownList1.SelectedValue;
myConnection.Open();
string query = ("SELECT sName from [dbo].[Table] WHERE (pName LIKE " + pNameTemp + ")");
SqlCommand sqlCmd = new SqlCommand(query, myConnection);
txtSkill.Text = sqlCmd.ExecuteScalar().ToString();
myConnection.Close();
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
it seems to search the correct name but when it comes to updating the txtSkill, I get the exception 'invalid column name' pop up, are there any obvious reasons as to why this is happening that i'm missing? any advice would be appreciated
In fact, you are missing '' for the parameter of the query.
Try to use this query.
SqlCommand sqlCmd = new SqlCommand(#"SELECT sName from [dbo].[Table] WHERE pName LIKE '{pNameTemp}'", myConnection);
But I recommend you to use SqlParameter in C# to avoid SQL Injection
SqlCommand com = new SqlCommand("SELECT sName from [dbo].[Table] WHERE pName LIKE #field", myConnection);
myConnection.Parameters.AddWithValue("#field", pNameTemp);
But normally, when we use LIKE, we should put in % because it gives all results contains keyword. LIKE without % doesn't make sense. So :
SqlCommand com = new SqlCommand("SELECT sName from [dbo].[Table] WHERE pName LIKE #field", myConnection);
command.Parameters.AddWithValue("#field", "'%" + pNameTemp + "%'");
There are some options in the LIKE clause:
%: The percent sign represents zero, one, or multiple characters
_ The underscore represents a single character
I have a database in MySQL Workbench with fields like (name, lastname, age, address, etc..) and a windows desktop application (a form) in visual studio with c# where you can insert, search and update.
When I insert data from the form and I leave some fields empty, they are saved in the database as blank and I want them to be saved as null.
Is there a way to make that happen?
Here is and insert button code:
conn = openconnection.GetConn();
MySqlCommand cmd = new MySqlCommand("INSERT INTO table_name (name,lastname,address, etc...) VALUES (' " + name_textbox.Text + " ',' " + lastname_textbox.Text + " ' etc... );", conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
Thanks a lot, it works fine but I have a problem with words with spaces, like: (father name , mother name , etc). When I insert a value at name it is fine but when I insert a value at father name or mother name it is null. I think it is because of space between words.
MySqlCommand cmd = new MySqlCommand("INSERT INTO table_name (name,`father name`,`mother name`, etc... VALUES (#name,#`father name`,#`mother name`,etc...);", conn);
cmd.Parameters.AddWithValue("#name", name_textbox.Text.NullString());
cmd.Parameters.AddWithValue("#`father name`", father_name_textbox.Text.NullString());
cmd.Parameters.AddWithValue("#`mother name`", mother_name_textbox.Text.NullString());
cmd.ExecuteNonQuery();
One way would be to simply do the interpretation on your own:
string.IsNullOrEmpty(name_textbox.Text) ? null : string.Format("'{0}'", name_textbox.Text);
However, I want to give you another option:
using (MySqlConnection conn = openconnection.GetConn())
{
using (MySqlCommand cmd = new MySqlCommand("INSERT INTO table_name (name,lastname,address) VALUES (#name,#lastname,#address);", conn);
{
cmd.Parameters.AddWithValue("#name", name_textbox.Text.NullString());
cmd.Parameters.AddWithValue("#lastname", lastname_textbox.Text.NullString());
cmd.Parameters.AddWithValue("#address", address_textbox.Text.NullString());
cmd.ExecuteNonQuery();
}
}
namespace System
{
public static class StringExtensions
{
public static string NullString(this string s)
{
return string.IsNullOrEmpty(s) ? null : s;
}
}
}
With this solution you'll be properly disposing the connection and command objects, but you'll also be able to streamline the string to null process and leverage prepared queries to make the process simpler and safer because it's not open to SQL Injection.
NOTE: the static class that you see should be placed in its own .cs file.
I like to use this nifty Function to test/insert DBNull.Value.
public static object ToDBNull(object value)
{
if (null != value)
return value;
return DBNull.Value;
}
Useful in other places but for your case:
MySqlCommand cmd = new MySqlCommand("INSERT INTO table_name (name,lastname,address, etc...)" +
"VALUES (' " + ToDBNull(name_textbox.Text) + " ',' " + ToDBNull(lastname_textbox.Text) + " ' etc... );", conn)
Also, you should consider your vulnerability to SQL injection attacks and consider Parameterized SQL command.
Though the columns appear as blanks in the database they are actually null. You can verify this by reading those fields in C# and comparing it with System.DBNull.
private void btnSubmit_Click(object sender, EventArgs e)
{
OleDbCommand cmd;
string cmdstring = "INSERT INTO Names (Surname,FName) VALUES('" + txtSurname.Text + "','" + txtFName.Text + "')";
OleDbConnection myConnection = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
cmd = new OleDbCommand(cmdstring, myConnection);
myConnection.Open();
cmd.ExecuteNonQuery();
myConnection.Close();
}
I want to add Surname and FName to access database, but an error has been shown like this "syntax error".
I don't know why.
Here are 2 possible reasons your query fails.
Names is a reserved word.
Surname or FName values which include an apostrophe.
You can avoid the first problem by enclosing the table name in square brackets ... [Names]. But if possible it would be better to choose a different name.
If you switch to a parameter query as others suggested, you can avoid the second problem. But in that case, still bracket the table name.
What is wrong in the following code? im storing the date n time into datetime field in sql server.
private void button1_Click(object sender, EventArgs e)
{
string d = DateTime.Now.ToShortDateString();
cmd.CommandText = "insert into trans values("+label9.Text+",'d');";
cmd.Connection = con;
con.Open();
int x= cmd.ExecuteNonQuery();
MessageBox.Show("Attendance recorded succesfully");
It is a very bad approach, because it opened for sql-injections. You better use SqlParameter.
cmd.CommandText="insert into trans values(#label, #date)";
cmd.Parameters.AddWithValue("label", int.Parse(label9.Text));
cmd.Parameters.AddWithValue("date", DateTime.Now);
cmd.Connection = con;
con.Open();
int x= cmd.ExecuteNonQuery();
There is mistyping in CommandText string. Use this instead
cmd.CommandText="insert into trans values("+label9.Text+","+DateTime.Now.ToString()+");";
EDIT:
Full edited code will be like this. Note that using statements will care for disposing your updates, but this code is still bad and a house of sql-injections. You must use parameters instead if you want safe code.
private void button1_Click(object sender, EventArgs e)
{
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection("Data Source=localhost; Initial Datalog=myDatabase; Integrated Security=TRUE;"))
{
using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("insert into trans values("+label9.Text+","+DateTime.Now.ToString()+");", connection))
{
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
}
Apart from the fact that you are using inline SQL, which is just bad. You should be using #param1 syntax in the query and then adding parameters to it instead (thus sidestepping this issue also). Even better - use an ORM like Linq to Sql or Entity Framework (or nHibernate or whatever).
SQL Server generally wants it's times in yyyymmdd format, and also you really should be checking the label's value is indeed an integer and only running the query if it is:
int labelValue = 0;
if(int.TryParse(label9.Text, out labelValue))
{
cmd.CommandText="insert into trans values("+ labelValue +
", '" + DateTime.Now.ToString("yyyyMMdd");"')";
cmd.Connection = con;
con.Open();
int x= cmd.ExecuteNonQuery();
MessageBox.Show("Attendance recorded succesfully");
}
I'd also say you really need to examine your usage of the connection/command - where do you Dispose? Judging by this code, I'm guessing you don't?
All in all, even with these fixes I'm not recommending you do things this way - do it the way that Harm suggests - the +5 (or more) there is deserved.
I'm attempting to insert an array into a SQL Server database. 1/4 is copied to the database before I receive the error:
Incorrect syntax near 's'. Unclosed
quotation mark after the character
string ', ')'.
Here is the button click event -
private void button3_Click(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Movies;");
sql.Open();
for (int i = 0; i < jointArray.Length; i++)
{
SqlCommand command = new SqlCommand("insert into [" + folderName + "] " + "values('" + jointArray[i].ToString() +"', '')", sql);
command.ExecuteNonQuery();
}
sql.Close();
}
I would hazard a guess that a 1/4 of the way through jointArray[i].ToString() contains an apostrophe.
So instead of a SQL query that looks like this..
insert into [MyFolder] values('MyValue')
you end up with something that looks like this
insert into [MyFolder] values('MyValue's')
which causes the error (notice where incorrect syntax near the s is!)
Please consider using parameters with your SQLCommand (look up Parameters.Add and Parameters.AddWithValue).
Using Parameters makes your code
More readable
Easier to debug
Less prone to SQL injection attacks (which recently got Sony Pictures hacked)
Looks like you might have apostrophes in your data, which is messing up your query.
This is a really bad approach. Unless you can guarantee that your data won't have any unexpected characters, you should be using SQL parameters at the very least to ensure they are interpreted correctly.
It is very likely that one of your array elements contains an apostrophe.
The problem is that you don't encode the string properly to be a string literal in SQL. When there is an apostrophe in the string it will break the syntax.
You should use a parameter instead of concatenating the string into the SQL code.
This will also allow you to reuse the same query and command object for all queries, instead of creating a new command for each query. You can also call Prepare on the command before the loop to reduce some of the overhead for each execution.
Example:
private void button3_Click(object sender, EventArgs e) {
using (SqlConnection sql = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Movies;")) {
sql.Open();
using (SqlCommand command = new SqlCommand("insert into [" + folderName + "] values(#P, '')", sql) {
SqlParameter param = command.Parameters.Add("#P", SqlDbType.VarChar, 50);
command.Prepare();
for (int i = 0; i < jointArray.Length; i++) {
param.Value = jointArray[i].ToString();
command.ExecuteNonQuery();
}
}
}
}
Checkout for the SQL escape characters like '
Somewhere in your values you have an unescaped single quote. Prob something like this should quick fix it.
SqlCommand command = new SqlCommand("insert into [" + folderName + "] " + "values('" + jointArray[i].ToString().Replace("'", "''") +"', '')", sql);
EDIT
Oops, paste error! Pasted what you had.