Use right syntax error in Mysql - c#

Am not able to fix the error below:
`"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'When,Then) values( '79','WBT-CoE','gyj','yi','yi')' at line 1"` error.
Here's the code:
protected void Button3_Click(object sender, EventArgs e){
string MyconnectionString = "server=localhost;database=requirement_doc;Uid=t;Pwd=123;";
MySqlConnection conn = new MySqlConnection(MyconnectionString);
MySqlCommand cmd;
DataTable dt1 = new DataTable();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT Req_ID, Actor FROM UseCase where Req_ID='" + txtReqID.Text + "' AND Actor='" + DropDownList1.Text + "'";
MySqlDataAdapter da1 = new MySqlDataAdapter();
da1.SelectCommand = cmd;
da1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
Label1.Text = "Data already exist";
}
else
{
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,When,Then) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
}
try
{
cmd.ExecuteNonQuery();
Label1.Text = " Successfully saved";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}

Surround When and then with `` because they are reserved names.
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,`When`,`Then`) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";

When and Then are reserved names in MySQL. So if you use those as column names, you get that error.

Related

connection string is not correct, how to fix it?

I'm using visual studio 2017 community and i'm trying to create local data base and I have a problem in the connection string since it dont connect when run it step by step its stuck in conn.Open();
this is the code of the connection and the executenonquery:
try
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOVI2R\SHILOVI2R\PHONENUM.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into phonebook(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle2", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
image screenshot of visual:
image screenshot
The entire code:
private void button1_Click(object sender, EventArgs e)
{
string strFilePat = #"C:\Users\oz\Desktop\sql\backup\tabel3.csv";
ConvertCSVtoDataTable(strFilePat, strFilePat);
}
public static DataTable ConvertCSVtoDataTable(string strFilePath, string conLocoldbString1)
{
MessageBox.Show("start", "SHILOV", MessageBoxButtons.OK);
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(strFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
try
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(??,???,?????,???? ?????,????,???? ?????,????,???,??)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
dt.Rows.Add(dr);
}
}
MessageBox.Show("finish", "SHILOVI2R", MessageBoxButtons.OK);
return dt;
}
}
}
Use the connection string available in properties tab of the screenshot you have attached if the problem is of connection string
This is what I'm talking about
Use this as connection string, also remember to replace password value from '*' to actual value.

Error connecting to Local Data Base i need to pass info from CSV file into the localdb table c#

I have an error message when I'm trying to run the code and pass the information from a CSV file into the Local DataBase
the error message is :
System.ArgumentException: 'Format of the initialization string does not conform to specification starting at index 0.'
and I'm not sure what is the problem in here:
SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','"
+ rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6]
+ "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
image screenshot of visual:
image screenshot
when I run the app the LOCALDBSHILOV have a red X on him is it noraml
red X image
the code is:
private void button1_Click(object sender, EventArgs e)
{
string strFilePat = #"C:\Users\oz\Desktop\sql\backup\tabel3.csv";
ConvertCSVtoDataTable(strFilePat, strFilePat);
}
public static DataTable ConvertCSVtoDataTable(string strFilePath, string conLocoldbString1)
{
MessageBox.Show("start", "SHILOV", MessageBoxButtons.OK);
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(strFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
try
{
SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('"
+ rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','"
+ rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
dt.Rows.Add(dr);
}
}
MessageBox.Show("finish", "SHILOVI2R", MessageBoxButtons.OK);
return dt;
}
Your connection string is not correct. Use one like this:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
when i run it its stuck in conn.Open(); and does nothing and there is no error but the application continues to run only that it does not pass to the next line of code and there is no update of the table
try
{
//SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOVI2R\SHILOVI2R\PHONENUM.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into phonebook(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle2", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}

how to insert date(long format) into access database using datetimepicker in c# ? (error is in date part only)

Error image is here
the error is in query line , its shows syntax error
try
{
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
command.CommandText = "insert into client_table(CLIENT, DATE,BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #" + dat.ToLongDateString() + "# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
this.Hide();
employee_form f1 = new employee_form("");
f1.ShowDialog();
}
thank you in advance
In Access, dates are delimited by #, not '. Also, Access does not recognize the long date format. But dates are not stored in any format so no worries, change it to:
... + "', #" + dat.ToString() + "# ...etc.
Although if you do not parameterize your query serious damage or data exposure can be done through SQL Injection because someone could type in a SQL statement into one of those textboxes that you are implicitly trusting.
Working example:
class Program
{
static void Main(string[] args)
{
System.Data.OleDb.OleDbConnectionStringBuilder bldr = new System.Data.OleDb.OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new System.Data.OleDb.OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#" + DateTime.Now.ToString() + "#)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
}
Update
However, you want to do something more like this which uses Parameters to protect against SQL Injection which is extremely easy to exploit so do not think that you don't really need to worry about it:
static void Main(string[] args)
{
OleDbConnectionStringBuilder bldr = new OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
OleDbParameter dobParam = new OleDbParameter("#dob", OleDbType.Date);
dobParam.Value = DateTime.Now;
cmd.Parameters.Add(dobParam);
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#dob)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
//code to write date in the access table.
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
//MessageBox.Show(dat.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
//command.CommandText = "insert into client_table(DATEE) values( '"dat.ToShortDateString()+"')";
command.CommandText = "insert into client_table (CLIENT, DATEE, BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #"+dat.ToShortDateString()+"# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
//New code for receiving the date between two range of dates
try
{
DateTime dat = this.dateTimePicker1.Value.Date;
DateTime dat2 = this.dateTimePicker2.Value.Date;
// MessageBox.Show(dat.ToShortDateString() + " " + dat2.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
string query;
query = "select * from client_table Where DATEE Between #" + dat.ToLongDateString() +"# and #" + dat2.ToLongDateString() + "# ";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection1.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
Thank you all of you for the support.

I want to get an alert if email already exits in my database in c# with help of execute scalar method

protected void btnSubmit_Click(object sender, EventArgs e)
{
string db = DropDownList1.SelectedItem.Value + "-" + DropDownList2.SelectedItem.Value + "-" + DropDownList3.SelectedItem.Value;
SqlConnection con = new SqlConnection("data source=BAN095\\SQLEXPRESS; database=Reg-DB; integrated security=SSPI");
SqlCommand cmd = new SqlCommand("select EmailID from Reg where EmailID='" + txtEmail.Text + "'", con);
con.Open();
Int32 count = (Int32)cmd.ExecuteScalar();
if (count==0)
{
Response.Write("email already Exists");
Response.End();
}
else
{
cmd.CommandText = "insert into Reg(FirstName,LastName,EmailID,PhoneNum,Gender,DOB)values('" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + "','" + txtMobile.Text + "','" + RdoGender.SelectedItem.Value + "','" + db + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
}
Please help me with this. And also for errors like use new keyword to create an object instance that I’m getting.
Put a unique index on EmailID, then perform just the insert and catch for SqlExceptions and check if exception.Number == 2601
Note: Use using statements to ensure that IDisposables will be disposed and use parameterized commands!
protected void btnSubmit_Click(object sender, EventArgs e)
{
string db = DropDownList1.SelectedItem.Value + "-" + DropDownList2.SelectedItem.Value + "-" + DropDownList3.SelectedItem.Value;
using(SqlConnection con = new SqlConnection("data source=BAN095\\SQLEXPRESS; database=Reg-DB; integrated security=SSPI"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("insert into Reg(FirstName,LastName,EmailID,PhoneNum,Gender,DOB)values(#FirstName,#LastName,#Email,#Mobile,#Gender,#Db)", con))
{
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
//Do the same with other parameters
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
if (ex.Number == 2601) // If instead of unique index, you have a unique constraint/primary key, check for ex.number==2627
{
// Duplicate key! Do whatever you want
}
}
}
}
}

i m getting error in the following cede. (System.Data.OleDb.OleDbException: ORA-00933: SQL command not properly ended)

protected void save_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
try
{
string connString = "Provider=OraOLEDB.Oracle;Data Source=127.0.0.1;User ID=SYSTEM;Password=SYSTEM;Unicode=True";
conn = new OleDbConnection(connString);
conn.Open();
string strQuery = "update login set fname ='" + TextBox4.Text + "' and lname='" + TextBox5.Text + "' and place='" + TextBox6.Text + "' and dob='" + TextBox7.Text + "' where uname='" + Label1.Text + "'";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
OleDbDataReader obReader = obCmd.ExecuteReader();
}
catch (OleDbException ex)
{
Response.Write("Send failure: " + ex.ToString());
}
catch (Exception exe)
{
Response.Write(exe.Message);
}
finally
{
if (null != conn)
{
conn.Close();
}
}
}
the update query syntax is wrong.
You cannot use AND while setting multiple columns. It should be seperated by comma.
string strQuery = "update login set fname ='" + TextBox4.Text + "',lname='" +
TextBox5.Text + "',place='" + TextBox6.Text + "',dob='" + TextBox7.Text +
"' where uname='" + Label1.Text + "'";
The values must be separated with a comma and there is one big problem in this code. Imagine what happens when someone puts the following into TextBox4:
' where 1 = 1 --
The result would be a table where all entries would be overwritten
update login set fname ='' where 1 = 1 --', lname='bla' ....
Use DbParameter instead:
string strQuery = #"
update LOGIN set
FNAME = :FNAME,
LNAME = :LNAME,
PLACE = :PLACE,
DOB = :DOB
where
UNAME = :UNAME
";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
obCmd.Parameters.AddWithValue(":FNAME", TextBox4.Text);
obCmd.Parameters.AddWithValue(":LNAME", TextBox5.Text);
obCmd.Parameters.AddWithValue(":PLACE", TextBox6.Text);
obCmd.Parameters.AddWithValue(":DOB", TextBox7.Text);
obCmd.Parameters.AddWithValue(":UNAME", Label1.Text);
OleDbDataReader obReader = obCmd.ExecuteReader();
For Oracle the : should indicate a parameter (it's a # for Sybase and MS SQL). I named all params like the target columns, but you can use other names of course.

Categories