problems entering data into mysql - c#

i have this code that is being used to enter data into mysql, but I have found an error that says:
"MySql.Data.MySqlClient.MySqlException: '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 ''11/05/2018)' at line 1'"
private void Button_Click(object sender, RoutedEventArgs e)
{
string especie = txt1.Text;
string nombre = txt2.Text;
string fechanac = txt3.Text;
string fecharev = txt4.Text;
int numanimales = 0;
int cont = 0;
var dbCon = DBConnection.Instance();
dbCon.DatabaseName = "animalia";
if (dbCon.IsConnect())
{
string query = "SELECT COUNT(*) FROM ANIMALES;";
var cmd = new MySqlCommand(query, dbCon.Connection);
numanimales = Convert.ToInt32(cmd.ExecuteScalar());
}
int id = numanimales + 1;
if (dbCon.IsConnect())
{
if (especie == "" || nombre == "" || fechanac == "" || fecharev == "")
{
MessageBox.Show("Introduzca todos los datos");
}
else
{
cont = 1;
MySqlDataReader reader;
string query = "INSERT INTO ANIMALES VALUES (" + id + ",FALSE,'" + especie + "','" + nombre + "','" + fechanac + "','" + fecharev + "');";
var cmd = new MySqlCommand(query, dbCon.Connection);
reader = cmd.ExecuteReader();
MessageBox.Show("Animal añadido");
reader.Close();
}
if (cont == 1)
{
this.Close();
}
}
}
}
The error appears in this part of the code
MySqlDataReader reader;
string query = "INSERT INTO ANIMALES VALUES (" + id + ",FALSE,'" + especie + "','" + nombre + "','" + fechanac + "','" + fecharev + ");";
var cmd = new MySqlCommand(query, dbCon.Connection);
reader = cmd.ExecuteReader();
MessageBox.Show("Animal añadido");
reader.Close();
Thank you very much in advance to those of you who can help me.

You are missing closing quotation marks on the last attribute:
...,'" + fecharev + ");";
should be
...,'" + fecharev + "');";

Related

syntax error missing operator in query expression c# using access as database

I'm getting syntax error in all my inputs into the textboxes.
In my database all the requirement is string other than the ID which is an autonumber, I try to search for possible answer but all didn't work or maybe I just missed some answer
Here is the error:
Syntax error (missing operator) in query expression ''hasdasd'password
= 'h'account_Type='Manager'Name='h'Middle_Name='h'Surname'h'address'h'BirthDate='3/17/1999'Mobile_Number'65465''.
Code:
private void update_Click(object sender, EventArgs e)
{
DateTime bdate = DateTime.Parse(birthdate.Value.ToShortDateString());
DateTime currentDate = DateTime.Parse(DateTime.Now.Date.ToShortDateString());
int age = currentDate.Year - bdate.Year;
String id = emp_view.SelectedRows[0].Cells[0].Value + String.Empty;
int id1 = Int32.Parse(id);
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\dbms\jollibee.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "update Employee_Details set username = '" + username.Text +
"'password = '" + password.Text +
"'account_Type='" + accountType.Text +
"'Name='" + name.Text +
"'Middle_Name='" + middlename.Text +
"'Surname'" + surname.Text +
"'address'" + address.Text +
"'BirthDate='" + birthdate.Value.ToShortDateString() +
"'Mobile_Number'" + mobilenumber.Text +
"'where ID = '" + id1 + "'";
if (username.Text.Equals("") ||
username.Text.Equals("") ||
password.Text.Equals("") ||
middlename.Text.Equals("") ||
surname.Text.Equals("") ||
address.Text.Equals("") ||
accountType.Text.Equals("") ||
mobilenumber.Text.Equals("")
)
{
MessageBox.Show("Please fill all fields.");
con.Close();
}
else if (age < 18)
{
MessageBox.Show("You are not allowed to work because you are under age..");
con.Close();
}
else
{
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(username.Text + "is now updated on database.");
list();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In your existing code, there are issues like.
1- Column in update are not separated by ","
2- All string are not separated using quotes ''
You should always avoid writing queries inline by concatenation of string. This will make you code vulnerable to SQL Injection.
To read more about SQL Injections check here
Change your code like following using command parameters.
cmd.CommandText = "update Employee_Details set [username] = #un, [password] = #pw, [account_Type]= #at, [Name] = #nm, [Middle_Name]= #mn, [Surname]= #sn, [address]= #add, [BirthDate] = #bd, [Mobile_Number] = #mn WHERE [Id]=#id";
cmd.Parameters.Add("#un", OleDbType.VarChar).Value = username.Text;
cmd.Parameters.Add("#pw", OleDbType.VarChar).Value = password.Text;
cmd.Parameters.Add("#at", OleDbType.VarChar).Value = accountType.Text;
cmd.Parameters.Add("#nm", OleDbType.VarChar).Value = name.Text;
cmd.Parameters.Add("#mn", OleDbType.VarChar).Value = middlename.Text;
cmd.Parameters.Add("#sn", OleDbType.VarChar).Value = surname.Text;
cmd.Parameters.Add("#add", OleDbType.VarChar).Value = address.Text;
cmd.Parameters.Add("#bd", OleDbType.Date).Value = Convert.ToDateTime(birthdate.Value);
cmd.Parameters.Add("#mn", OleDbType.VarChar).Value = mobilenumber.Text;
cmd.Parameters.Add("#id", OleDbType.VarChar).Value = id1;
Note: You need to correct the datatype based on your table structure as it is now known to me.
Your completely malformed SQL should look like:
cmd.CommandText = "update Employee_Details set " +
"username = '" + username.Text + "',"+
"[password] = '" + password.Text + "'," +
"account_Type = '" + accountType.Text + "'," +
"[Name] = '" + name.Text + "'," +
"Middle_Name = '" + middlename.Text + "'," +
"Surname = '" + surname.Text + "'," +
"address = '" + address.Text + "'," +
"BirthDate = #" + birthdate.Value.ToString("yyyy'/'MM'/dd") + "#," +
"Mobile_Number = '" + mobilenumber.Text + "' " +
"where ID = " + id1 + "";
That said, DO use parameters as already explained. Much easier and safer.

sql missing comma

protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ("+ ID + "," + password + "," + name + "," + position + "," + accessRight + "," + status + "," + createOn + "," +loginID+ ")";
readdata.updateData(sqlcommand);
}
I am passing the sqlcommand to readdata class for execute..and its throw me this error..
ORA-00917: missing comma
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: ORA-00917:
missing comma.
The readdata class function code as below.
public void updateData(string SqlCommand)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
OleDbCommand cmd = new OleDbCommand(SqlCommand, conn);
OleDbDataAdapter daPerson = new OleDbDataAdapter(cmd);
conn.Open();
cmd.ExecuteNonQuery();
}
Given that most of your columns are variable-length character, they must be enclosed in single quotes.
So, instead of:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES (" + InputValue + ")";
You would, at minimum, need this:
string sqlcommand = "INSERT INTO myTable (ColumnName) VALUES ('" + InputValue + "')";
The result of the first statement, for an InputValue of "foo", would be:
INSERT INTO myTable (ColumnName) VALUES (foo)
which would result in a syntax error.
The second statement would be formatted correctly, as:
INSERT INTO myTable (ColumnName) VALUES ('foo')
Additionally, this code seems to be using values entered directly by the user, into txtID, txtPassword, and so on. This is a SQL Injection attack vector. Your input needs to be escaped. Ideally, you should use parameterized queries here.
This appears to be c#. Please update your tags accordingly.
At any rate, if it is .Net, here is some more information about parameterizing your queries:
OleDbCommand.Parameters Property
OleDbParameter Class
Try this
string sqlcommand = "INSERT INTO USERMASTER (USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES ('"+ ID + "','" + password + "','" + name + "','" + position + "','" + accessRight + "','" + status + "','" + createOn + "','" +loginID+ "')";
Concatenating the query and executing it is not reccomended as it may cause strong SQl Injection. Suppose if any one of those parameters contain a comma(,) like USERPWD=passwo',rd then query will devide it as passwo and rd by the comma. This may be a problem
It is recommended that you use "Parameterized queries to prevent SQL Injection Attacks in SQL Server" and hope it will resolve your issue.
Your code can be rewritten as follows
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
string loginID = (String)Session["UserID"];
string ID = txtID.Text;
string password = txtPassword.Text;
string name = txtName.Text;
string position = txtPosition.Text;
int status = 1;
string createOn = validate.GetTimestamp(DateTime.Now); ;
string accessRight;
if (RadioButton1.Checked)
accessRight = "Administrator";
else
accessRight = "Non-administrator";
if (txtID.Text != "")
ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + ID + "ha " + password + "ha " + status + "ha " + accessRight + "ha " + position + "ha " + name + "ha " + createOn + "');", true);
string strQuery;
OleDbCommand cmd;
strQuery = "INSERT INTO USERMASTER(USERID,USERPWD,USERNAME,USERPOISITION,USERACCESSRIGHTS,USERSTATUS,CREATEDATE,CREATEUSERID) VALUES(#ID,#password,#name,#position,#accessRight,#status,#createOn,#loginID)";
cmd = new OleDbCommand(strQuery);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#position", position);
cmd.Parameters.AddWithValue("#accessRight", accessRight);
cmd.Parameters.AddWithValue("#status", status);
cmd.Parameters.AddWithValue("#createOn", createOn);
cmd.Parameters.AddWithValue("#loginID", loginID);
bool isInserted = readdata.updateData(cmd);
}
rewrite your updateData data as follows
private Boolean updateData(OleDbCommand cmd)
{
string strConString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
OleDbConnection conn = new OleDbConnection(strConString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}

Error on Looping mssql statment using c# windows form

I am trying to check whether database have the following data before making decision to update or insert but current i have a problem not able to loop through as it only execute once.
//It is suppose to loop based on the value in account.devices.Count --> last tried with 10 values
for (int z = 0; z < account.devices.Count; ) have 10 data inside account.device.Count
{
SqlCommand checkForDevice = new SqlCommand("select * from status where device = '" + account.devices[z].deviceid + "' and Dates = '" + DateTime.Now.ToString("yyyy-MM-dd") + "'", myConnection);
SqlDataReader myReader = checkForDevice.ExecuteReader();
if (myReader.Read())
{
String sqlStatus = myReader["status"].ToString().Trim();
myReader.Close();
if (sqlStatus.Equals(account.devices[z].state.ToString()))
{
}
else
{
}
}
else
{
//SqlCommand myCommand = new SqlCommand("INSERT INTO records(device,Dates,Time,status ) Values (" + account.devices[i].deviceid + ","+DateTime.Now.ToString("yyyy-MM-dd") + "','" + DateTime.Now.ToString("HH:mm:ss") + "','" +account.devices[i].state+")", myConnection);
Console.Write("CALLED");
}
Console.Write("LOOP");
z++;
}
Thanks in advance
Update working codes
try
{
for (int z = 0; z < account.devices.Count; )
{
SqlCommand checkForDevice = new SqlCommand("select * from status where device = '" + account.devices[z].deviceid + "' and Dates = '" + DateTime.Now.ToString("yyyy-MM-dd") + "'", myConnection);
SqlDataReader myReader = checkForDevice.ExecuteReader();
if (myReader.Read())
{
String sqlStatus = myReader["status"].ToString().Trim();
if (sqlStatus.Equals(account.devices[z].state.ToString()))
{
}
else
{
}
}
else
{
//SqlCommand myCommand = new SqlCommand("INSERT INTO records(device,Dates,Time,status ) Values (" + account.devices[i].deviceid + ","+DateTime.Now.ToString("yyyy-MM-dd") + "','" + DateTime.Now.ToString("HH:mm:ss") + "','" +account.devices[i].state+")", myConnection);
Console.Write("CALLED");
}
Console.Write("LOOP");
myReader.Close();
z++;
}
}
catch(Exception e)
{
this.listBox1.BeginInvoke((MethodInvoker)delegate()
{
listBox1.Items.Add(DateTime.Now.ToString("hh:mm:ss tt") + " [DB Insert] " + e.ToString());
this.listBox1.SelectedIndex = listBox1.Items.Count - 1;
this.listBox1.SelectedIndex = -1;
});
}

c#-The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I'm new to .net development
I'm trying to fetch the data from Facebook app,when update the query I'm getting the above error on update customer details
in 'cust_date' filed and i taken in cust_date datatype is DATETIME.
so how to convert this DATETIME format to 'MM/DD/YYYY HH:MM'
public void Customer(string Customerid)
{
var accessToken = "CAACEdEose0cBAMTINaTZCrm67pT6cO16KHsR3UNgOTZAGH03GHmhKozUOxEXYpL3ZB9pfbFWm4Oj2VMVy8xMf5vXMpFtY6LZm2Hej0WmrHPlwk7pWyibf9gXbCaDBoIih26nRqffAfwZD";
var client = new FacebookClient(accessToken);
string clientfeed = client.Get(Customerid).ToString();
JObject obj = JObject.Parse(clientfeed);
string custid = obj["id"].ToString();
string name = obj["name"].ToString();
string fst_name = obj["first_name"].ToString();
string lst_name = obj["last_name"].ToString();
string link = obj["link"].ToString();
string[] splitlink = link.Split('/');
if (splitlink[3].StartsWith("profile"))
{
splitlink[3] =name.ToString();
link = splitlink[0] + '/' + splitlink[1] + '/' + splitlink[2] + '/' + splitlink[3];
}
string gender = obj["gender"].ToString();
string cust_updated_time = obj["updated_time"].ToString();
string abctime = cust_updated_time.Substring(0, cust_updated_time.ToString().Length - 3);
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
myConnection.Open();
string qy3 = "select count(*) from fb_customer where customer_fb_id='" + custid + "'";
string count;
SqlCommand myCommand = new SqlCommand(qy3, myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
count = myReader[0].ToString();
int cnt = Convert.ToInt32(count);
if (cnt == 0)
{
SqlConnection myOleConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy = "select * from fb_customer";
myOleConnection.Open();
SqlCommand myOleCommand = new SqlCommand(qy, myOleConnection);
myOleCommand.CommandText = "SET DATEFORMAT MDY insert into fb_customer(customer_fb_id,name,firstname,lastname,link,gender,cust_date,New) values('" + custid + "','" + name + "','" + fst_name + "','" + lst_name + "','" + link + "','" + gender + "','" + abctime + "','1')";
SqlDataReader myOleDataReader = myOleCommand.ExecuteReader();
myOleDataReader.Close();
myOleConnection.Close();
}
else
{
SqlConnection myOleDb = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myOleDb.Open();
SqlCommand mycmd = new SqlCommand(qy1, myOleDb);
mycmd.CommandText = " UPDATE fb_customer set name='" + name + "',firstname='" + fst_name + "',lastname='" + lst_name + "',link='" + link + "',gender='" + gender + "',cust_date= '" + abctime + "' where customer_fb_id = '" + custid + "'";
SqlDataReader mydatareader = mycmd.ExecuteReader();
mydatareader.Close();
myOleDb.Close();
}
}
myReader.Close();
myConnection.Close();
}
public void IIPLCustomer(string iiplcustid, string abctime)
{
var accessToken = "CAACEdEose0cBADKYiSkFVcqeZAYxmYlytKM5pQT6zuEvnNoU9soPlWc2pZAJvKDL557BKTGIRNhbcuZBR6Li8TlrcM8yG1yXYGzikVlUPyFgDPzEDMiIZAnuHe5y3gTZCxkyTeA12ISPPRhJev6B63rTr05slMfwZD";
var client = new FacebookClient(accessToken);
string clientfeed = client.Get(iiplcustid).ToString();
JObject obj = JObject.Parse(clientfeed);
string custid = obj["id"].ToString();
string name = obj["name"].ToString();
string[] splitname = name.Split(' ');
string link = obj["link"].ToString();
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
myConnection.Open();
string qy = "select count(*) from fb_customer where customer_fb_id='" + custid + "'";
string count;
SqlCommand myCommand = new SqlCommand(qy, myConnection);
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
count = myReader[0].ToString();
int cnt = Convert.ToInt32(count);
if (cnt == 0)
{
SqlConnection myConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myConnection1.Open();
SqlCommand myCommand1 = new SqlCommand(qy1, myConnection1);
myCommand1.CommandText = "SET DATEFORMAT MDY insert into fb_customer(customer_fb_id,name,link,firstname,lastname,cust_date,New) values('" + custid + "','" + name + "','" + link + "','" + splitname[0] + "','" + splitname[1] + "','" + abctime + "','1')";
SqlDataReader myReader1 = myCommand1.ExecuteReader();
myReader1.Close();
myConnection1.Close();
}
else
{
SqlConnection myOleDb = new SqlConnection(ConfigurationManager.ConnectionStrings["IIPLDOTNETConnectionString"].ConnectionString);
string qy1 = "select * from fb_customer";
myOleDb.Open();
SqlCommand mycmd = new SqlCommand(qy1, myOleDb);
mycmd.CommandText = "SET DATEFORMAT MDY UPDATE fb_customer set name='" + name + "',firstname='" + splitname[0] + "',lastname='" + splitname[1] + "',link='" + link + "',cust_date='" + abctime + "' where customer_fb_id = '" + custid + "'";
//Here I'm getting an error
SqlDataReader mydatareader = mycmd.ExecuteReader();
mydatareader.Close();
myOleDb.Close();
}
}
myReader.Close();
myConnection.Close();
}
You can use Datetime.ParseExact method to convert date into appropriate format. Use like this
DateTime.ParseExact('07-12-2013', 'dd/MM/yyyy',
System.Globalization.CultureInfo.InvariantCulture).ToString('yyyy/MM/dd')
You need to change the format whatever you like.
This is gonna be very simple. Try the following format.
string date = DateTime.Now.ToString("MM/dd/yyyy HH:MM");
I just gave DateTime.Now and converted it. You can give the DateTime which you get and convert it to the format specified in the above syntax.

Proper way to perform the INSERT statement from C# to MySQL

I created this function that inserts new records -- I submit query directly to it.
My question- is it optimal? It is it fool proof and guaranteed to function normally? If not; please advise.
static String Server = "";
static String Username = "";
static String Name = "";
static String password = "";
static String conString = "SERVER=" + Server + ";DATABASE=" + Name + ";UID=" + Username + ";PASSWORD=" + password + ";connect timeout=500000;Compress=true;";
public bool InsertSQL(String Query)
{
int tmp = 0;
try
{
using (MySqlConnection mycon = new MySqlConnection(conString))
{
using (MySqlCommand cmd = new MySqlCommand(Query, mycon))
{
mycon.Open();
try
{
tmp = cmd.ExecuteNonQuery();
}
catch
{
if (mycon.State == ConnectionState.Open)
{
mycon.Close();
}
}
mycon.Close();
}
}
}
catch { return tmp > 0 == true ? true : false; }
return tmp > 0 == true ? true : false;
}
This is my SQL insert that I create in other function and pass as text to insert function. I am open to all suggestions!
String insertSql = #"INSERT INTO `gps_unit_location`
(`idgps_unit`,`lat`,`long`,`ip`,`unique_id`,
`loc_age`,`reason_code`,`speed_kmh`,
`VehHdg`,`Odometer`,`event_time_gmt_unix`,`switches`, `engine_on_off`, `dt`)
VALUES
(
(Select idgps_unit from gps_unit where serial=" + serial + "),'" + lat + "','" + lon + "','" + IP + "','" + unique_id + #"',
'" + LocAge_mins + "','" + ReasonCode + "','" + Speed + #"',
'" + VehHdg + "','" + Odometer + "','" + EventTime_GMTUnix + "','" + Switches + "', '" + engine_on_off + #"', DATE_ADD(NOW(), INTERVAL 1 HOUR))
";
I built this answer using your code as the example. Take note of the following line:
cmd.Parameters.AddWithValue("#queryParam", Query);
It is always a best-practice to code for potential SQL Injection attacks even if they are unlikely to happen.
static String Server = "";
static String Username = "";
static String Name = "";
static String password = "";
static String conString = "SERVER=" + Server + ";DATABASE=" + Name + ";UID=" + Username + ";PASSWORD=" + password + ";connect timeout=500000;Compress=true;";
public bool InsertSQL(String Query)
{
int tmp = 0;
try
{
using (MySqlConnection mycon = new MySqlConnection(conString))
{
using (MySqlCommand cmd = new MySqlCommand(Query, mycon))
{
mycon.Open();
try
{
cmd.Parameters.AddWithValue("#queryParam", Query);
tmp = cmd.ExecuteNonQuery();
}
catch
{
if (mycon.State == ConnectionState.Open)
{
mycon.Close();
}
}
mycon.Close();
}
}
}
catch { return tmp > 0 == true ? true : false; }
return tmp > 0 == true ? true : false;
}
By making this so generic, you are leaving yourself open to SQL injection. I am guessing you have to build the query and insert values directly. SQL parameters would be better here, you could potentially pass in a params of SqlParameters, however that would still rely on generic text being sent and still leaves you open to an injection.
Here is a SQL Parameter example

Categories