Error in C# insert statement for SQL Server - c#

I am trying to pass an insert statement in a C# Winforms to SQL Server. I keep getting a syntax error that just doesn't make sense to me
error in syntax near "("
My syntax is perfectly fine, as when I copy and paste into SQL Server Mgmt Studio, the code runs perfectly.
Any help would be greatly appreciated!
Thanks!
try
{
using (var cmd = new SqlCommand("INSERT INTO " + intodrop.SelectedText + "(" + colnamedrop.SelectedText.ToString() + "," +
colnamedrop2.SelectedText.ToString() + ") " + "VALUES" + " (" + valuebox.Text + ");"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#tbl", intodrop.SelectedText);
cmd.Parameters.AddWithValue("#colname", colnamedrop.SelectedText);
cmd.Parameters.AddWithValue("#values", valuebox.Text);
cmd.Parameters.AddWithValue("#colname2", colnamedrop2.SelectedText);
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}

Check if SelectedText property returns right values. Try to use Text property instead.
var cmd = new SqlCommand("INSERT INTO " + intodrop.Text +
"(" + colnamedrop.Text + ',' + colnamedrop2.Text + ") "
+ "VALUES" + " (" + valuebox.Text + ");")

You missed comma between column names when insert sql statement preparing. When printing you have comma and display correctly.
Concatenated sql statement without any inputs validation is widely open for sql injection attacks. Try to use parameter as much as possible.

It looks like you are trying to insert values to two columns, but you are appending them like this "Col1+Col2", instead of "Col1+','+Col2".
using (var cmd = new SqlCommand("INSERT INTO " + intodrop.SelectedText + "(" + colnamedrop.SelectedText.ToString() + ','+
colnamedrop2.SelectedText.ToString() + ") " + "VALUES" + " (" + valuebox.Text + ");"))
I hope this resolves the issue.

First try hard coding your insert value after that change it based on your need. Confirm the column data types are assigned correctly.
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Property ( FolioNo,PropertyType) VALUES (001,'WIP')"))
{
cmd.Connection = con;
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}

1) You should have two texbox for entering your values. If no column names you gray the value of column 1, ditto for column 2.
This allows you not to have to enter quote (do not forget to make an escape quotes
2) use the string.format function for more readability
try
{
//Add columns selected
List<string> Mycolumns = new List<string>();
If (! string.IsNullOrEmpty(colnamedrop.Text)) Mycolumns.Add(colnamedrop.Text);
If (! string.IsNullOrEmpty(colnamedrop2.Text)) Mycolumns.Add(colnamedrop2.Text);
//Add values selected with escaped quoted and string quoted
List<string> Myvalues ​​= new List<string>();
If (! string.IsNullOrEmpty(colvalue1.Text)) Myvalues.Add("'" + colvalue1.Text.Replace("'", "''") + "'");
If (! string.IsNullOrEmpty(colvalue2.Text)) Myvalues.Add("'" + colvalue2.Text.Replace("'", "''") + "'");
//If nothing selected, no action
if (Mycolumns.Count==0 && Myvalues.Count==0) return;
//Build query
String Query = string.Format ( "INSERT INTO {0} ({1}) VALUES ({2})", intodrop.Text, string.Join(Mycolumns, ", "), string.Join(Myvalues, ", "));
//Execute query
using (var cmd = new SqlCommand(Query, con ))
{
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
con.Close();
}
}
catch (Exception g)
{
MessageBox.Show("Error during insert: " + g.Message);
}

Related

Isert new row in sql dosn't accept text

I want to insert new row in my database from user input, i use C# and sql insert syntax. My problem is when i run a program all field compltely fill except text value (name of the product) which fill with another number (price) i check the syntax and the code but it's never work.
public DataBaseManager (string DataBaseFilename)
{
strFileName = DataBaseFilename;
strFileNamenopath = System.IO.Path.GetFileName(strFileName);
strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.IO.Path.GetFullPath(strFileName).Replace(System.IO.Path.GetFileName(strFileName), "") + "; Extended Properties=dBase III;Mode=ReadWrite";
conn = new OleDbConnection(strAccessConn);
conn.Open();
}
public void AddData(string Column, string value)
{
try
{
int i = 0;
char[] delimiterChars = { ','};
queryCutting = #"INSERT INTO [" + strFileNamenopath + "] ( " + Column + " ) VALUES ( " + value + " )";
OleDbCommand cmd = new OleDbCommand(queryCutting, conn);
string[] _valseperated = value.Split(delimiterChars);
string[] _columnsbase = Column.Split(delimiterChars);
foreach (string str in _columnsbase )
{
cmd.Parameters.AddWithValue(str,SqlDbType.VarChar).Value = _valseperated[i];
i++;
}
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
private void AddnewCode_Buttion_Click(object sender, RoutedEventArgs e)
{
_productBase.AddData("code, pv1, achat, designat", "123456789" + ", " + Textbox_Achat.Text + ", " + Textbox_Achat.Text +", " + Produitsnom_TextBox.Text);
}
Value of column represent the column name in databse , value is the text box value.
Column = "code, pv1, achat, designat";
Value = "123456789, 10, 10, Productname";
value of queryCutting
queryCutting = "INSERT INTO [produits.dbf] ( code, pv1, achat, designat ) VALUES ( 123456789, 540, 120, NewProduct)"
I think I have understood your problem. You set the Value string directly in the query text so you should get this result
"INSERT INTO [theFolderName] (code, pv1, achat, designat)
VALUES ( 123456789, 10, 10, Productname )";
The first three values are accepted as correct values for the numeric fields and no parameter is taken in consideration for these fields, but when the parser reaches the ProductName "value" it cannot use as a value because it is not a inside quotes. So it thinks it is a parameter and searches the Parameters collection. Because in OleDb parameters are positional, it takes the first parameter and passes its value to the OleDbCommand. And the first parameter is the Code.
This should solve the problem. Don't give a parameter name (OleDb doesn't care) and let the OleDbCommand use the complete set of parameters given in the exact order expected
public void AddData(string Column, string value)
{
try
{
char[] delimiterChars = { ','};
// Query text is incomplete, we complete it inside the loop
queryCutting = #"INSERT INTO [" + strFileNamenopath + #"]
( " + Column + " ) VALUES ( ";
// The query and the connection will be set after the loop
OleDbCommand cmd = new OleDbCommand();
string[] _valseperated = value.Split(delimiterChars);
string[] _columnsbase = Column.Split(delimiterChars);
foreach (string str in _columnsbase )
{
// The second parameter in AddWithValue is the Value not the type.
cmd.Parameters.AddWithValue(str, _valseperated[i]);
// Add a placeholder for each parameter
queryCutting += "?,";
}
// Remove the ending colon an close the paren on the query text
queryCutting = queryCutting.Substring(queryCutting.Length-1) + ")";
cmd.CommandText = queryCutting;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Notice that this code doesn't solve your Sql Injection problem. You should be absolutely sure that your user doesn't type itself neither the file name/folder neither the name of the columns and choose these values from a whitelisted set of values
I solved the problem by add insering Produitsnom_TextBox.Text betwwen qutes like this
_productBase.AddData("code, designat ,pv1, achat", "123456789" + ", " + "' " +Produitsnom_TextBox.Text + "'" + ", " + Vente_TextBox.Text + ", " + Textbox_Achat.Text );
also i removed the parametes part.
public void AddData(string Column, string value)
{
try
{
int i = -1;
char[] delimiterChars = { ',' };
queryCutting = #"INSERT INTO [" + strFileNamenopath + "] ( " + Column + " ) VALUES ( " + value + " )";
OleDbCommand cmd = new OleDbCommand(queryCutting, conn);
MessageBox.Show(queryCutting);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Syntax Error Ocurring on the Data Reader

try
{
int i = 0;
using (SqlConnection sqlCon = new SqlConnection(Form1.connectionString))
{
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
// MessageBox.Show(commandString);
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
i = 1;
if (i == 0)
{
MessageBox.Show("Error in Logging In!", "Error");
}
MessageBox.Show("Successfully Logged In");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I'm making a LoginForm for a Project.I have created a table which shows the LoginDetails(Account,ID,LoginTime,LogoutTime).But when I run the Program,it doesn't runs successfully.I face an error which is in Pic-2.When I remove sql 'data reader',the program runs without displaying the error.
When you concatenate a null it basically adds nothing to the string, so this code:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
results of this string, and as you can see it has an extra comma, that causes the exception:
"INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('acc',textbxID,, SYSDATETIME());"
If you want to add NULL to the query it has to be a string, so do this instead:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID + ", NULL , SYSDATETIME()" + ");";
And you are using ExecuteReader instead of ExecuteNonQuery. You cannot use ExecuteReader for inserting rows to the DB.
Also, as someone mentioned in the other answer, you better do it with parametes to avoid SQL Injections.

C# Creating and Populating an Oracle Database

To start i don't have access to the database, we hit a problem with our university account and waiting for it to be reset. How ever i do have code that is giving me some problems and frankly i'm not sure i have even gone about this in the right way.
I am only trying to make a simple test program that creates a table, populates it then reads it.
If this isn't enough information i am sorry i should of waited but its bugging me getting these little errors in the code before i even get to a point i can compile to test tomorrow.
Here is the code to create the table, there does not seem to be any errors in the code
static void buildTable()
{
try
{
string sqlBuild = "CREATE TABLE Item ("
+ "Item_ID VARCHAR2(1),"
+ "Item_Name VARCHAR2(16),"
+ "Price_Consumer VARCHAR(5)"
+ " ); ";
OracleCommand cmd = new OracleCommand(sqlBuild, con);
Connect();
cmd.ExecuteNonQuery();
Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Here is the code to populate the table and this is where i am getting errors.
static void populateTable()
{
string[,] items;
items = new string[5,3] { { "1", "Mozzarella", "9.99" }, { "2", "Peperoni", "12.99" }, { "3", "Meat Feast", "14.99" }, { "4", "Chicken Tikka", "12.99" }, { "5", "Spicy Vegetarian", "11.99" } };
try
{
OracleCommand cmd = new OracleCommand();
OracleDataReader r = cmd.ExecuteReader();
r.Read();
for (int i = 1; i < 6; i++)
{
for(int j = 1; j < 4; j++)
{
OracleCommand comd = new OracleCommand();
comd.Connection = con;
comd.CommandText = "insert into Item(Item_ID, Item_Name, Price_Consumer) values(" items[i, j].ToString() + ", " + items[i, j].ToString() + ", " + items[i, j].ToString() ");";
Connect();
comd.ExecuteNonQuery();
Close();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
the errors are on the items[i,j], it tells me it expects an " ; "
lastly this is what im near 100% will work as this i have done in the past, but i have never tried to use c# to create or populate a table.
static void itemList()
{
string s = "\n";
try
{
Connect();
OracleCommand cmd = new OracleCommand(sql, con);
OracleDataReader r = cmd.ExecuteReader();
r.Read();
while (r.Read())
{
s = s + r["Item_ID"].ToString() + ", " + r["Item_Name"].ToString() + ", " + "£" +r["Price_Consumer"].ToString();
}
Close();
Console.WriteLine(s);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
here is the addtional code that might be relevant
static void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=username;Password=password;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=host)(PORT=port))(CONNECT_DATA=(SERVICE_NAME=SID)))";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
static void Close()
{
con.Close();
con.Dispose();
}
Declarations
static OracleConnection con;
static string sql = "select * from Item";
Your internal loop is not needed. When you try to insert a row, you don't call the insert one time for each column, but you call the insert one time for each row
Another problem are your columns of type VARCHAR, this means that you need to insert strings there, but you don't do it correctly.
This could be solved putting single quotes around those string to be recognized as such by the database engine.
for (int i = 1; i < 6; i++)
{
comd.CommandText = #"insert into Item(Item_ID, Item_Name, Price_Consumer)
values('" + items[i, 0].ToString() + "', '" +
items[i, 1].ToString() + "', '" +
items[i, 2].ToString() '");";
However while this will work for your simple example, this is still wrong. You should never concatenate string to build an sql command. This leads to Sql Injection and to a parsing error if the value to insert contains a single quote.
The only correct way to do it is through a parameterized query as this
comd.CommandText = #"insert into Item(Item_ID, Item_Name, Price_Consumer)
values(:ID, :Name, :Price)";
comd.Parameters.AddWithValue(":ID", items[i, 0].ToString());
comd.Parameters.AddWithValue(":Name",items[i, 1].ToString());
comd.Parameters.AddWithValue(":Price",items[i, 2].ToString());
(As a side benefit, look at how the command is more understandable now)
This line is not well formatted and is missing two + symbols:
comd.CommandText = "insert into Item(Item_ID, Item_Name, Price_Consumer) values(" +
items[i, j].ToString() + ", " +
items[i, j].ToString() + ", " +
items[i, j].ToString() + ");";
If you split it in a similar way to the above then it is easier to spot the errors
You are missing a '+' sign here

how to create a table having spaces between the words?

I am trying to create a table using code.
Here is my code.
private void btnOK_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE "+"" + rchtxtFieldCode.Text + " "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "" + ")";
SqlCommand cmd = new SqlCommand(s, con);
if (cmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("created");
}
con.Close();
}
It is creating the table if the table name has single word.. It is showing exception if there is space between the words(eg: Sales Info)
If this is for SQL Server you use square brackets:
string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " ([" + rchFieldTitle.Text + "] " + combDataType.Text + "" + ")";
In fact you should always use square brackets to stop these kind of errors happening.
Also ensure you are sanitising your strings otherwise you might have SQL injection issues.
Just add Box braces:
string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "" + ")";
//^_______________________________^
Do not use spaces in table or field names.In this, Try to change query with Square brackets i.e.
For example ,
sqlString = "CREATE TABLE [All Students]"
use this code, i think it will give you the desire output.
private void btnOK_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE '"+rchtxtFieldCode.Text + "'(" +"'"+rchFieldTitle.Text +"'" + combDataType.Text + "" + ")";
SqlCommand cmd = new SqlCommand(s, con);
if (cmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("created");
}
con.Close();
}

I tried to insert data in mysql database using C# txtbox form but I always got an error?

This is my code I think I am doing right so far but I really dunno what is the problem.
I am making a register form with txtbox for username and password I encrypt the password with MD5, I tried deleting the MD5 encryption thinking that it might be the prtoblem but still when I deleted it the problem is still occur.
ApareceCrudLib a = new ApareceCrudLib("localhost", "root", "", "cashieringdb");
string query = "INSERT INTO register (username,password) " +
"VALUES(" +
"'" + txtUser.Text + "'," +
"MD5('" + txtPass.Text +"')";
a.mysqlInsert(query);
MessageBox.Show("Account has been registered!");
this.Close();
This is the code for my class ApareceCrudLib for mysqlInsert
public void mysqlInsert(string query)
{
try
{
if (this.Open())
{
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.ExecuteNonQuery();
this.Close();
System.Windows.Forms.MessageBox.Show("Record Inserted!");
}
}
catch { this.Close(); System.Windows.Forms.MessageBox.Show("INSERT Record Error!"); }
return;
}
as you can see I catch the error with dialog box so basically if it will fail to insert or connect to database the message box shows "INSERT Record Error!". By the way there is no error in visual studio only in inserting to database.
I think the error somewhere in the code for inserting database string query = "INSERT
INTO register (username,password) " +
"VALUES(" +
"'" + txtUser.Text + "'," +
"MD5('" + txtPass.Text +"')";
maybe a comma a semi-colon a period I am clueless.
Hi!rhughes here is the image of the error!
you must add a ")" to your string query.
string query = "INSERT INTO register (username,password) " +
"VALUES(" +
"'" + txtUser.Text + "'," +
"MD5('" + txtPass.Text +"'))";
^ HERE
The SQL is not correct. You have two opening "(" and only one closing.
In order to see the actual error, try this:
try
{
if (this.Open())
{
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.ExecuteNonQuery();
this.Close();
System.Windows.Forms.MessageBox.Show("Record Inserted!");
}
}
catch(Exception ex)
{
this.Close();
System.Windows.Forms.MessageBox.Show(String.Format("INSERT Record Error! {0}", ex.Message));
}

Categories