can someone help me what is wrong with my code? It always says "Syntax error in INSERT INTO statement. "
try
{
OleDbConnection Con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\MotoFix.mdb;");
Con.Open();
OleDbCommand Com = new OleDbCommand();
Com.Connection = Con;
Com.CommandText = "INSERT INTO Order VALUES ('" + txtRandomOrder.Text + "','" + txtCode.Text + "')";
Com.ExecuteNonQuery();
Con.Close();
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
}
Order is a keyword in msaccess refer this link
http://office.microsoft.com/en-us/access-help/access-2007-reserved-words-and-symbols-HA010030643.aspx
change your statement to
"INSERT INTO [Order] VALUES ('" + txtRandomOrder.Text + "','" + txtCode.Text + "')";
and see if it works
Related
I'm trying to get the users details in the text boxes in my form to my database in access, which should save. However i keep getting an error message every time i click to register, the following code is how i am trying to write it out:
public void AddNewUser()
{
string filePath;
try
{
filePath = (Application.StartupPath + ("\\" + DBFile));
connection = new System.Data.OleDb.OleDbConnection((ConnectionString + filePath));
connection.Open();
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error");
}
finally
{
connection.Close();
}
}
However I think that the problem is actually coming from this section:
// ---set the user's particulars in the table---
string sql = ("UPDATE enroll SET SSN=\'"
+ (txtSSN.Text + ("\', " + ("Name=\'"
+ (txtName.Text + ("\', " + ("Company=\'"
+ (txtCompany.Text +("\', "
+ (" WHERE ID=" + _UserID))))))))));
command.CommandText = sql;
command.ExecuteNonQuery();
MessageBox.Show("User added successfully!", "Error");
Really your query is unreadable. Any kind of error could hide in that jungle of string concatenation and single quotes sprawled everywhere. (like a not necessary comma escaped probably from a fixup of a copy/paste operation)
You should use parameterized query and all of this will disappear
command.Connection = connection;
string sql = "UPDATE enroll SET SSN=?, Name=?, Company=? WHERE ID=?";
command.CommandText = sql;
command.Parameters.AddWithValue("#p1", txtSSN.Text);
command.Parameters.AddWithValue("#p2", txtName.Text );
command.Parameters.AddWithValue("#p3", txtCompany.Text);
command.Parameters.AddWithValue("#p4", _UserID);
command.ExecuteNonQuery();
Now I think that this is really more readable, no quotes to add because the framework knows the datatype of every parameter and will use the appropriate quoting required. Last but not least, no problem with Sql Injection
New to WPF. I want to edit the values of a database row that are displayed in textboxes. At the moment I am getting an error: "ExecuteNonQuery:Connection property has not been initialized". When I remove the where clause all rows are updated and not just the selected item.
private void btnEDIT_Click(object sender, RoutedEventArgs e)
{
try
{
sc.Open();
cmd = new SqlCommand("Update Rewards set Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'where Name = '" + this.txtName.Text +"'");
cmd.ExecuteNonQuery();
MessageBox.Show("Update Successfull");
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You haven't set the Connection property of SqlCommand. So the command does not know where to connect. Use the constructor overload from SqlCommand or set it separate like this
cmd.Connection = sc;
cmd = new SqlCommand("Update Rewards set Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'where Name = '" + this.txtName.Text +"'",sc); // add connection here
also You should use parametrized queries or Stored Procedures that will prevent SQL Injection attacks.
SqlCommand cmd = new SqlCommand("Update Rewards set Name = #name, Cost= #cost where Name = #name ,sc);
cmd.Parameters.AddWithValue("#name", Convert.ToString(this.txtName.Text)); and so on
I hope this is what you need :) Copy paste this. Good luck bro! :) If you have question, just ask, I'll answer if I know LOL :)
private void btnEDIT_Click(object sender, RoutedEventArgs e)
{
try
{
sc.Open();
sql = "UPDATE REWARDS SET Name = '" + this.txtName.Text + "', Cost= '" + this.txtCost.Text + "'WHERE Name = '" + this.txtName.Text +"'");
SqlCommand command = new SqlCommand(sql, con);
command.ExecuteNonQuery();
MessageBox.Show("Update Successfull");
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a problem when I run my code "without YearlyLimit" then it is run properly but when i add the YearlyLimit in insert query then error occurs
"Number of query values and destination fields are not the same."
protected void btn_Save_Click(object sender, EventArgs e)
{
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Geeta/Desktop/eTimeTrackLite1.mdb;Persist Security Info=False;");
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string query = "insert into LeaveTypes (LeaveTypeFName,LeaveTypeSName,YearlyLimit,Gender) values ('" + txt_leavetypename.Text + "', '" + txt_shortname.Text + "', '" + txt_yearlimit.Text + "', '" + Convert.ToString(rdbtn_all.Checked) + "', '" + Convert.ToString(rdbtn_male.Checked) + "', '" + Convert.ToString(rdbtn_female.Checked) + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.ExecuteNonQuery();
conn.Close();
BindGridData();
}
You are trying to add too many items into the record
LeaveTypeFName
LeaveTypeSName
YearlyLimit
Gender
You are trying to insert
txt_leavetypename.Text
txt_shortname.Text
txt_yearlimit.Text
Convert.ToString(rdbtn_all.Checked)
Convert.ToString(rdbtn_male.Checked)
Convert.ToString(rdbtn_female.Checked)
you need to make a check on which item you want to go into the last field
I have a window in WPF. When I user enter name, I want to insert it to database and get USERID.
private void button1_Click(object sender, RoutedEventArgs e)
{
OleDbDataReader rd;
string name=comboBox1.Text;
OleDbConnection conn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|CellBiology.mdb;Persist Security Info=
True");
string sql = "select * from UserInformation where UserName='" + name+ "'";
conn.Open();
OleDbCommand cmd = new OleDbCommand(sql, conn);
rd = cmd.ExecuteReader();
if (rd.Read())
{
string id = rd["UserID"].ToString();
MessageBox.Show(id);
}
else
{
string sql2 = "insert into UserInformation(UserName) values ('" + ad+ "')";
OleDbCommand ne = new OleDbCommand(sql2, conn);
ne.ExecuteNonQuery();
**the problem is here.**
}
I believe you are never initializing the variable ad you are using in the following SQL:
string sql2 = "insert into UserInformation(UserName) values ('" + ad+ "')";
Which is a problem.
I am storing an image in a table in varbinary(max) format, actually first time it will be empty, I am checking whether it is empty of not but while checking for null field I am getting any exception stating invalid cast so can any one suggest what is the problem with this.
code sample is
con = new SqlCeConnection(CommonClass.ConnectionStringStartup);
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT Signature,UserId FROM UserMaster Where " +
" LoginName = '" + UserName + "' " +
" AND Password = '" + Password + "'";
cmd.CommandType = CommandType.Text;
// MessageBox.Show(UserName);
SqlCeDataReader dr;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
{
if (dr.IsDBNull(0))
SignLoaded = false;
else
SignLoaded = true;
}
Thanks in advance
With regards
Bharath kumar
To me, it looks like this should work?
Have you tried Convert.IsDbNull( dr.GetValue(0))?
Otherwise I can only suggest using dr.GetValue(0) and look at the result.
Cheers