I have been trying to figure out why my program keeps giving me error. system.data.oledb.oledbexception(0x80040E14): Syntax error in INSERT INTO statement.
Table name: User
Columns:
Username
AccountNumber
FirstName
LastName
Code:
namespace Library_System
{
public partial class CreateAccountWindow : Form
{
OleDbConnection connect = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jc\Documents\Visual Studio 2013\Projects\Library System\Library System\LibrarySystemDatabase.accdb;Persist Security Info=False;");
OleDbCommand command = new OleDbCommand();
//OleDbDataReader reader;
public CreateAccountWindow()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string Username = "", AccountNumber = "", FirstName = "", LastName = "";
//int Borrowed = 0;
bool hasValue1 = false, hasValue2 = false, hasValue3 = false, hasValue4 = false;
if (textBox1.Text != "")
{
label1.Hide();
Username = textBox1.Text;
hasValue1 = true;
}
else
{
label1.Show();
label1.Text = "Required";
}
if (textBox10.Text != "")
{
label21.Hide();
AccountNumber = textBox8.Text;
hasValue2 = true;
}
else
{
label21.Show();
label21.Text = "Required";
}
if (textBox8.Text != "")
{
label13.Hide();
FirstName = textBox10.Text;
hasValue3 = true;
}
else
{
label13.Show();
label13.Text = "Required";
}
if (textBox7.Text != "")
{
label12.Hide();
label12.Text = "Required";
LastName = textBox7.Text;
hasValue4 = true;
}
else
{
label12.Show();
label12.Text = "Required";
}
if (hasValue1 || hasValue2 || hasValue3 || hasValue4)
{
try
{
connect.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "insert into User (Username,AccountNumber,FirstName,LastName) values ('" + Username + "','" + AccountNumber + "','" + FirstName + "','" + LastName + "')";
command.ExecuteNonQuery();
MessageBox.Show("REGISTRATION COMPLETE !!", "DONE");
connect.Close();
}
catch (Exception ex)
{
connect.Close();
MessageBox.Show("Error:"+ex.ToString());
}
}
}
}
You are getting the error because USER is a reserved word in Access SQL so you need to enclose the table name in square brackets. Also, as marc_s mentioned in a comment to the question, you should be using a parameterized query like this:
// test data
string Username = "gord";
string AccountNumber = "gt001";
string FirstName = "Gord";
string LastName = "Thompson";
command.CommandText =
"INSERT INTO [User] (Username, AccountNumber, FirstName, LastName) VALUES (?,?,?,?)";
command.Parameters.AddWithValue("?", Username);
command.Parameters.AddWithValue("?", AccountNumber);
command.Parameters.AddWithValue("?", FirstName);
command.Parameters.AddWithValue("?", LastName);
command.ExecuteNonQuery();
You will need a UNIQUE field as primary key.
Fields that generate numbers automatically in Access
SelectCommand = "select ##IDENTITY";
var id = (int)SelectCommand.ExecuteScalar();
did you try to run the insert query directly on db console? in your case its access. you might be having some spelling mistake.
you have initialized oledbcommand object twice. you might not require to initialize it just after oledbconnection object.
also regarding the approach you can use the validators; check this link How to: Validate Data
for oledbcommand parameters check below links:
OleDBParams
Update Data using OLEDB
Insert data using OLEDB
Related
I am trying to do lock user account for Invalid login attempts in Asp.Net C# by using Visual Studio 2019. Database is using MySql Workbench 8.0 CE. But facing the error
C# code shown as below:
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace Canteen_UAT
{
public partial class LoginDetail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
MySqlConnection scon = new MySqlConnection("server = XXX.XXX.XX.XXX; user id = root; password = XXXXX; persistsecurityinfo = True; database = posdbms_uat");
String myquery = "select count(*) from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = myquery;
cmd.Connection = scon;
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
String uname;
String pass;
String status;
//String lockstatus;
int attemptcount = 0;
if (ds.Tables[0].Rows.Count > 0)
{
uname = ds.Tables[0].Rows[0]["username"].ToString();
pass = ds.Tables[0].Rows[0]["password"].ToString();
status = ds.Tables[0].Rows[0]["status"].ToString();
scon.Close();
if (status == "Open")
{
if (uname == TextBox1.Text && pass == TextBox2.Text)
{
Session["username"] = uname;
Response.Redirect("Order.aspx");
}
else
{
Label2.Text = "Invalid Username or Password - Relogin with Correct Username & Password. No of Attempts Remaining : " + (2 - attemptcount);
attemptcount = attemptcount + 1;
}
}
else if (status == "Locked")
{
Label2.Text = "Your Account Locked Already : Contact Administrator";
}
else
{
Label2.Text = "Invalid Username or Password - Relogin wit Correct Username and Password.";
}
if (attemptcount == 3)
{
Label2.Text = "Your Account Has Been Locked Due to Three Invalid Attempts - Contact Administrator.";
setlockstatus(TextBox1.Text);
attemptcount = 0;
}
}
}
private void setlockstatus(String username1)
{
String mycon = "server = xxx; user id = root; password = xxx; persistsecurityinfo = True; database = posdbms_uat";
String updatedata = "Update posdbms_uat.logindetail set status='Locked' where username='" + username1 + "' ";
MySqlConnection con = new MySqlConnection(mycon);
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = updatedata;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
}
Not sure what might be causing this.
What I have tried:
I created a table as posdbms_uat, datatable match the column name in the database table and with appropriate datatype. Not sure how this error pops up.
The query:
String myquery = "select count(*) from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
...only returns the number of rows matching the WHERE condition - not the actual data in the rows. It should be fixed by specifying the columns you want to get:
String myquery = "select username, password, status from posdbms_uat.logindetail where username='" + TextBox1.Text + "'";
Also, you should consider using parametrization to avoid SQL injection (see this SO question). Another thing is, please do not store the password in plain text.
private void btnSubmit_Click(object sender, EventArgs e)
{
if (textBox2.Text != "")
{
string path = textBox2.Text;
string StudentNumber = "";
string FirstName = "";
string LastName = "";
string Grade = "";
string Section = "";
string Letter = "";
OleDbConnection my_con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=#" + path + ";Extended Properties=Excel 12.0;");
my_con.Open();
OleDbCommand icmd = new OleDbCommand("SELECT * FROM [dataGridView1_Data$]", my_con);
OleDbDataReader dr = icmd.ExecuteReader();
while (dr.Read())
{
StudentNumber = dr[0].ToString();
FirstName = dr[1].ToString();
LastName = dr[2].ToString();
Grade = dr[3].ToString();
Section = dr[4].ToString();
Letter = dr[5].ToString();
MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog='studentinfo';username=root;password=");
connection.Open();
MySqlCommand icmmd = new MySqlCommand("INSERT INTO studenttable(StudentNumber, FirstName, LastName, Grade, Section, Letter)VALUES(#a,#b,#c,#d,#e,#f)", connection);
icmmd.Parameters.AddWithValue("a", StudentNumber);
icmmd.Parameters.AddWithValue("b", FirstName);
icmmd.Parameters.AddWithValue("c", LastName);
icmmd.Parameters.AddWithValue("d", Grade);
icmmd.Parameters.AddWithValue("e", Section);
icmmd.Parameters.AddWithValue("f", Letter);
icmmd.ExecuteNonQuery();
connection.Close();
}
MessageBox.Show("data Imported");
textBox2.Text = "";
}
else if (textBox2.Text == "")
{
}
I am getting a OleDb exception
(Cannot update. Database or object is read-only).
I am trying to insert the csv to my mysql table.
Tried this fromcode here[To insert csv file into mysql database table using c# windows form. I still new to c# and mysql.
So I am currently puzzled to the logic of my program, I have ran through it multiple times but I am not too sure. I basically want to be able to notify the user saying that the contact number they have entered already exists in the database. I have gotten close I am sure as I have done a lot of research but I do not think what I have done is actually checking the database but rather just telling it to match to anything that is in the textbox rather than checking the database.
Just to clarify I do not want to extract data from the database and put it into the textbox. Thanks.
Update: Two different programs for two different suggested solutions.
(Possible Solution 1) Updated contact number is unique method using COUNT:
private void CheckContactNumber()
{
string checkContactNum = "SELECT COUNT(*) FROM Employee WHERE ContactNumber = " + addContactNum.Text + " "; //01234567890
OleDbCommand cmd = new OleDbCommand(checkContactNum, conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
int countDup = (int)dr[0];
if (countDup > 0 && addContactNum.Text != "")
{
err += "Contact number is already listed in the database\r\n";
errorContactNum.Visible = true;
uniqueContactNumber = false;
}
else if (countDup == 0 && addContactNum.Text != "")
{
errorContactNum.Visible = false;
uniqueContactNumber = true;
}
}
conn.Close();
}
(Possible Solution 2)Update to 2nd suggested solution:
if (err == "")
{
// you miss s here
string addEmployee = "if not exists(select LastName from Employee where LastName = #LastName)INSERT INTO Employee(FirstName, LastName, Role, DateOfHire, ContactNumber)" +"VALUES(#FirstName, #LastName, #Role, #DateOfHire, #ContactNumber)";
OleDbCommand cmd = new OleDbCommand(addEmployee, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = addFirstName.Text;
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = addLastName.Text;
cmd.Parameters.Add("#Role", OleDbType.VarChar).Value = addRole.Text;
cmd.Parameters.Add("#DateOfHire", OleDbType.VarChar).Value = addDateOfHire.Text;
cmd.Parameters.Add("#ContactNumber", OleDbType.VarChar).Value = addContactNum.Text;
conn.Open();
// i removed the duplicated code
if (cmd.ExecuteNonQuery() != 1)
{
err += "Contact number is already listed in the database\r\n";
errorContactNum.Visible = true;
}
conn.Close();
addFirstName.Text = String.Empty;
addLastName.Text = String.Empty;
addRole.Text = String.Empty;
addContactNum.Text = String.Empty;
addRole.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
}
//Save It
else
{
MessageBox.Show(err);
}
}
So this would be acceptable for adding to my database as all criterion is met but it doesnt accept it, I'm assuming it runs the else code right at the bottom of AddEmployee method
Here is an Image of my database which is linked to my program.
update your function from your end
private void CheckContactNumber()
{
string checkContactNum = "SELECT COUNT(*) FROM Employee WHERE ContactNumber = " + addContactNum.Text + " "; //01234567890
OleDbCommand cmd = new OleDbCommand(checkContactNum, conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
//if (dr.Read() && addContactNum.Text != "")
if (dr.Read())
{
int count = (int)dr[0];
if(count>0)
{
err += "Contact number is already listed in the database\r\n";
errorContactNum.Visible = true;
uniqueContactNumber = false;
}
}
conn.Close();
}
Updated Answer
private void CheckContactNumber()
{
DataSet myDataSet = new DataSet();
try
{
string strAccessSelect = "select count(*) from Employee where ContactNumber='" + addContactNum.Text + "'";
OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect, conn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
conn.Open();
myDataAdapter.Fill(myDataSet, "Employee");
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
return;
}
finally
{
conn.Close();
}
DataTable dt = myDataSet.Tables[0];
if (dt != null)
{
if (int.Parse(dt.Rows[0][0].ToString()) > 0)
{
string err = "Contact Number Already exist..";
}
}
}
You can merge two codes in one code , by using if not exist method in sql server like this
string addEmployee = "if not exists(select LastName from Employee where
LastName=#LastName)INSERT INTO Employee (FirstName, LastName, Role,
DateOfHire, ContactNumber)" +"VALUES (#FirstName, #LastName, #Role, #DateOfHire, #ContactNumber)";
if (cmd.ExecuteNonQuery()!=1){
// the employee exist in database
}
When I enter user name and password, it logs in successfully and also opens desired field but when I enter wrong name or password (not saved in DB) it shows nothing actually it should encounter "else" this is the code
private void signin_button_Click(object sender, EventArgs e)
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= D:/Student_Managment_System/SMS1.mdb";
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
string usrname = name_textBox.Text;
string passwd = pass_textBox.Text;
OleDbCommand cmd1 = new OleDbCommand("select * from Manager where Name='" + usrname + "' and Passwd='" + passwd + "'");
OleDbDataReader Reader = cmd1.ExecuteReader();
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
else
{
MessageBox.Show("Inviled User name or password");
}
}
myConnection.Close();
}
Your else statement isn't executed because there are no values to read when an invalid username or password is entered. You need to check if your reader has any rows. See here
Code
//Are there any rows
if(Reader.HasRows)
{
//If so read them
while (Reader.Read())
{
if (Reader[5].ToString() == "manager")
{
this.Hide();
Student_Info stuInf = new Student_Info();
stuInf.Show();
break;
}
else if (Reader[5].ToString() == "employee")
{
MessageBox.Show("log in as a employee ");
}
}
}
else
{
MessageBox.Show("Inviled User name or password");
}
if (txtUsername.Text != "")
{
string q = "insert into info(Username) values ('" + txtUsername.Text.ToString() + "')";
dosomething(q);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
if (txtPassword.Text != "")
{
string a = "insert into info(Password) values ('" + txtPassword.Text.ToString() + "')";
dosomething(a);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
private void dosomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
cn.Close();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Every time I run this it always show that error. I dont know how to fix it.
The code should record the data i put in a textbox to ms access database. plz helpp
Presumably, you've initialized cn somewhere by doing something like
cn = new SqlConnection();
You need to pass the connection string for the database to the constructor:
cn = new SqlConnection("your connection string here");
or set it sometime later, before you connect:
cn.ConnectionString = "your connection string here";