Inserting array into SQL Server database problems - c#

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.

Related

SQL command string is it okay to concatenate it?

I've been creating a class for buttons where you can add and delete rows from the table's database but it is my first time concatenate a string I have a suspicion that it is not working due to commandtext.
public static void deleteButton(string databaseName, string IDname, DataGridView dgv)
{
Helper.openConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Helper.cn;
string IDLocation = dgv.SelectedRows[0].Cells[0].Value.ToString();
cmd.CommandText = "delete from " + databaseName + " where " + IDname + " = " + IDLocation;
Helper.cn.Close();
MessageBox.Show("Successfully Deleted!");
}
public static void addButton(string databaseName, List<string> values, DataGridView dgv, bool isAdd)
{
Helper.openConnection();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Helper.cn;
string message = isAdd == true? "Sucessfully Added" : "Sucessfully Edited";
string command = "insert into " + databaseName + " values(";
for (int i = 0; i < values.Count; i++)
{
command += values[i];
if(i != values.Count - 1) command += ", ";
}
command += ")";
cmd.CommandText = command;
MessageBox.Show(message);
Helper.cn.Close();
}
thank you for your time helping me.
Two problems:
You're using INSERT INTO [databaseName]. That should be INSERT INTO [tableName]. That's why it's not working.
Don't concatenate values into the SQL text. It opens the door for SQL injection, and it also makes it harder for the SQL server to reuse query plans. Instead, use query parameters. There is an example in the documentation.
I'll leave the design up to you and just attempt to answer the question. Have you actually looked at the command text? Have you tried to paste the command text into a query and run it manually? You need to quote string values. Also your functions and query use 'databaseName'. This should be a table name not a database name.
The commentary here is all on target, but that aside the key issue with your code is you are not doing anything. You have opened the connection, declared the SQL command, but then you don't execute it.
So yes, use parameters, but if you want your SQL to work you need to execute it:
string IDLocation = dgv.SelectedRows[0].Cells[0].Value.ToString();
cmd.CommandText = string.Format("delete from {0} where IDname = #ID", databaseName);
cmd.Parameters.AddWithValue("#ID", IDLocation);
Note you don't need quotes or anything when you use parameters, even on a non-numeric datatype.
And the feature of the evening, the missing link:
cmd.ExecuteNonQuery();
Same goes for your insert query -- be sure to run the execute method, and USE PARAMETERS!

Simple, ordinary SQL Server insert method

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();

save a decimal value in database c#

I am trying to save a value from text box into sql database. I am having the error as shown on the picture. my code below:
public void datastore()
{
string Blerje, Shitje, Data;
Blerje = usdollar_buy.Text;
Shitje = usdollar_sell.Text;
Data = dateTimePicker.Text;
try
{
string constring = "Data Source=DELL;Initial Catalog=login_register;Integrated Security=True";
/* Declaring Connection Variable */
SqlConnection con = new SqlConnection(constring);
String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] values ('" + Blerje + "','" + Shitje + "','" + Data + "')";
/* Checking Connection is Opend or not If its not open the Opens */
if (con.State != ConnectionState.Open)
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
/* Executing Stored Procedure */
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Te dhenat u ruajten ne databaze");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
1. You might be having more columns in your table than mentioned values(3) in your query.
so it is always good to specify the column names in your query for which columns you are inserting the values.
Try This:
INSERT INTO [TableName](COL1,COl2,COL3)
Values(Value1,Value2,Value3);
2. As you mentioned your columsn are decimals, you are inserting them as as strings by enclosing the values within single quotes.
You should not enclose the decima values within single quotes.
Suggestion : Your query is open to SQL Injection Attacks.
I Would suggest you to use the Parameterised queries to avoid them.
You are missing the fields in your insert statement.
The database will try to determine the right columns and their order, but if you don't deliver all fields in the appropriate order, your query will fail.
So in short:
Deliver all fields in the correct order;
Or: add the fields you want to fill in the insert.
Sample:
String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] (Blerje, Shitje, Data) values ('" + Blerje + "','" + Shitje + "','" + Data + "')";
change the datatype to (18,6) or so, whichever is suitable for you,
The second part of decimal data type shows how many digits do you require after the 'point'. In your case it's '0', so db is rounding it to nearest integer.
Source: http://msdn.microsoft.com/en-us/library/ms187746.aspx

Syntax error in UPDATE statement OleDb Exception

I check my SQL Statement many times and it seems that my SQL Statement is Error. I don't why it doesn't work. My SQL Statement is correct and It resulted to this OleDBException "Syntax error in UPDATE statement.".
Here is the code
OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString);
CN.Open();
cmd1 = new OleDbCommand("Update Mosque Set Name='" + txtNAME.Text + "', No='" + Convert.ToInt32(txtNO.Text) + "', place='" + txtPlace.Text + "', group='" + txtGroup.Text + "', description='" + txtdec.Text + "' where id='" + txtID.Text + "'", CN);
cmd1.ExecuteNonQuery();
CN.Close();
need help please to know what is the error here
I don't know what database are you using, but I am sure that GROUP is a reserved keyword in practically any existant SQL database. This word cannot be used without some kind of delimiter around it. The exact kind of delimiter depend on the database kind. What database are you using?
Said that, please do not use string concatenation to build sql commands, but use always a parameterized query. This will allow you to remove any possibilities of Sql Injection and avoid any syntax error if one or more of your input string contains a single quote somewhere
So, supposing you are using a MS Access Database (In Access also the word NO is a reserved keyword and the delimiters for reserved keywords are the square brakets) you could write something like this
string commandText = "Update Mosque Set Name=?, [No]=?, place=?, " +
"[Group]=?, description=? where id=?"
using(OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString))
using(OleDbCommand cmd1 = new OleDbCommand(commandText, CN))
{
CN.Open();
cmd1.Parameters.AddWithValue("#p1",txtNAME.Text);
cmd1.Parameters.AddWithValue("#p2",Convert.ToInt32(txtNO.Text));
cmd1.Parameters.AddWithValue("#p3",txtPlace.Text);
cmd1.Parameters.AddWithValue("#p4",txtGroup.Text);
cmd1.Parameters.AddWithValue("#p5",txtdec.Text);
cmd1.Parameters.AddWithValue("#p6",txtID.Text);
cmd1.ExecuteNonQuery();
}
Instead for MySQL you have to use the backticks around the GROUP keyword
string commandText = "Update Mosque Set Name=?, No=?, place=?, " +
"`Group`=?, description=? where id=?"
Hard to tell without knowing the values of the texboxes, but I suspect that one of them has an apostrophe which is causing an invalid syntax.
I recommend using parameters instead:
cmd1 = new OleDbCommand("Update Mosque Set [Name]=#Name, [No]=#No, [place]=#Place, [group]=#Group, [description]=#Description WHERE id=#ID", CN);
cmd1.Parameters.AddWithValue("#Name",txtNAME.Text);
cmd1.Parameters.AddWithValue("#No",Convert.ToInt32(txtNO.Text));
// etc.

How to execute a TSQL input command in C# which includes a string with "-", "\" or ";"

I have a SqlCommand that attempts to insert a row in a SQL Server database table. The column of interest is a nvarchar(100) and the data that needs to be input will include characters such as "-", ";" and "\". When I insert a string without these characters everything works fine. When I attempt to insert a string that includes these characters the code fails because these characters are literally understood by the code and thus reports a syntax error. I have resolved such an issue in TSQL alone using dynamic sql, however I cannot find any good references to perform this action in C#. I suppose I could create a stored procedure and pass the values, but is there a way in which I could efficiently perform this using C# alone? If so, How? Or is passing values to a Stored Procedure a better approach?
Here is a simplified version of the code:
String SQLServerInstanceNames = "ussqlclus-db43\ussqlclusdb43; ussqlclus-db44\ussqltrysdb44; ussqltrys-db45\ussqltrysdb45;"
//Create Connection (Get Connection string from Server Explorer)
SqlConnection myConnection = new SqlConnection("Data Source=SERVER1;Initial Catalog=Database1;Integrated Security=True");
//Open connection
try { myConnection.Open(); }
catch (Exception e) { Console.WriteLine(e.ToString()); }
SqlCommand myCommand = new SqlCommand("INSERT INTO [dbo].[Table1]" +
"([SQLServerInstanceNames])" +
"VALUES (SQLServerInstanceNames);", myConnection);
//Execute command
myCommand.ExecuteNonQuery();
//Close connection
try { myConnection.Close(); }
catch (Exception e) { Console.WriteLine(e.ToString()); }
Try with SqlParameters. It will save you from Sql Injection as well as from your current problem.
myCommand.Parameters.AddWithValue("#param1", myValueWithCharacters);
C# uses \ as a control character. You can ignore those by prepending the string with an # character:
String SQLServerInstanceNames = #"ussqlclus-db43\ussqlclusdb43; ussqlclus-db44\ussqltrysdb44; ussqltrys-db45\ussqltrysdb45;"
Just update your code like this to include parmeters in INSERT statement
SqlCommand myCommand = new SqlCommand("INSERT INTO [dbo].[Table1]" +
"([SQLServerInstanceNames])" + "VALUES (#SQLServerInstanceNames);", myConnection);
myCommand.Parameters.AddWithValue("#SQLServerInstanceNames", "instance name");
Notice I updated VALUES part and added #SQLServerInstanceNames – this is how you add parameters to your query.
Now that you use parameters you won’t have to worry about special characters. These will be handled automatically.

Categories

Resources