Error - Insert data into Access database in c# - c#

Pls, am having an error code when inserting data into Access database. It keeps saying there's sytanx error in my INSERT INTO statement. Can any one help me to solve this.
Here is the code
try {
OleDbConnection connection = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\DELL\Documents\EmployeesData.accdb;
Persist Security Info = false;");
connection.Open();
OleDbCommand cmd = new OleDbCommand("insert into EmployeeInfo (UserName, Password) values('" + UserText.Text + "', '" + PassText.Text + "')", connection);
cmd.ExecuteNonQuery();
MessageBox.Show("Inserted");
}
catch (Exception ex)
{
MessageBox.Show("Failed" + ex.ToString());
}

Password is a keyword in MSACCESS so u need to enclosed in [] bracket
OleDbCommand cmd = new OleDbCommand("insert into EmployeeInfo ([UserName], [Password])
values('" + UserText.Text + "', '" + PassText.Text + "')", connection);
Note: always use parameterized queries to avoid SQL Injection

Related

when i fire insert query i get Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll

I am new to this forum and new to C# web programming. I am developing LMS (Library Management system) using SQL Server and Visual Studio ver 16. I have an issue with the insertion of data into the database. the same code I used in other pages and work perfectly. put hardcoded values in insert statement and it worked perfectly which means that there is no issue with connection to database so where is the issue? it can be the text boxes etc name and property which I also checked and found correct. code is as follows
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
// SqlCommand cmd = con.CreateCommand();
//cmd.CommandType = CommandType.Text;// beow is the way to write a query like ist put '' then iside we have "" and then isde we have ++ and then inside we have text box name
// cmd.CommandText= "INSERT INTO member_master_tbl values('"++"','"++"','"++"','"++"','"++"','"++"','"++"','"++"','"++"')"
// cmd.CommandText = "INSERT INTO member_master_tbl (full_name,dob,contact_no,email,state,city,pincode,full_address,member_id,password) values ('" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() + "','"+TextBox4.Text.Trim()+"','" + TextBox3.Text.Trim() + "','" + DropDownList1.SelectedItem.Value + "','" + TextBox6.Text.Trim() + "','" + TextBox7.Text.Trim() + "','" + TextBox5.Text.Trim() + "','" + TextBox8.Text.Trim() + "','" + TextBox9.Text.Trim() + "');";
//notr thr col nsmes in the query are case sensitive
String status = "pending";
SqlCommand cmd = new SqlCommand("INSERT INTO member_master_tbl (full_name,dob,contact_no,email,state,city,pincode,full_address,member_id,password,account_status)values(#full_name,#dob,#contact_no,#email,#state,#city,#pincode,#full_address,#member_id,#password,#account_status);", con);
cmd.Parameters.AddWithValue("#full_name", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#dob", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("#contact_no", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("#email", TextBox4.Text.Trim());
cmd.Parameters.AddWithValue("#state", DropDownList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#city", TextBox6.Text.Trim());
cmd.Parameters.AddWithValue("#pincode", TextBox7.Text.Trim());
cmd.Parameters.AddWithValue("#full_address", TextBox5.Text.Trim());
cmd.Parameters.AddWithValue("#member_id", TextBox8.Text.Trim());
cmd.Parameters.AddWithValue("#password", TextBox9.Text.Trim());
cmd.Parameters.AddWithValue("#account_status",status);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('Sign Up Successful. Go to User Login to Login');</script>");
}
catch (SqlException ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}

Syntax error in INSERT INTO command on Visual Studio

I have an easy insert query, but visual studio return "Syntax error in INSERT INTO command", i copy+paste the exact same query in the db (access) and it work... Any help??
public void Create(string mail, string nickname, string password, string avatar)
{
OleDbConnection cn = new OleDbConnection(_connectionString);
OleDbCommand cmd = new OleDbCommand();
try
{
String PwdSHA256;
SHA256 mySHA256 = SHA256.Create();
byte[] hashValue = mySHA256.ComputeHash(Encoding.UTF8.GetBytes(password));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hashValue.Length; i++)
{
builder.Append(hashValue[i].ToString("x2"));
}
PwdSHA256 = builder.ToString();
cn.Open();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO utenti ([email],[nickname],[password],[avatar],[attivo]) " +
"VALUES ('" + mail + "', '" + nickname + "', '" + PwdSHA256 + "','', false)";
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Session["errore"] = ex;
System.Web.HttpContext.Current.Response.Redirect("ErrorPage.aspx");
this._errore = ex.Message;
}
finally
{
cmd = null;
cn.Close();
}
}
Using SQL queries directly in your code is not a good coding practice, use SQL procedures and pass the parameters to SQL.
And be clear, the error you are facing is an execution time error or a compilation.
Use dbo.Your_DB_Name.utenti or Your_DB_Name.utenti instead of utenti.
Wrap up your 'false'
Are you still using PwdSHA256 encryption
Maybe you should change
cmd.CommandText = "INSERT INTO utenti (email,nickname,password,avatar,attivo) " +
"VALUES ('" + mail + "', '" + nickname + "', '" + PwdSHA256 + "','', false)";
And make sure your column in database is same with your query

SQL Server INSERT Command doesn't insert data

I want to insert the content of some textboxes into a SQL Server database.
This is the code I use:
SqlConnection myConn = new SqlConnection(myConnection);
myConn.Open();
SqlCommand InsertCommand = new SqlCommand("INSERT INTO invmgmt.Products (product_id, product_name, product_price, possible_discount, product_in_stock) VALUES ('" + Convert.ToInt32(tbAddProdID.Text) + "','" + tbAddProdName.Text + "','" + Convert.ToDouble(tbAddProdPrice.Text) + "','" + Convert.ToInt32(tbAddPblDiscount.Text) + "','" + Convert.ToInt32(tbAddInStock.Text) + "')");
myConn.Close();
If I execute that, nothing happens to the database, does anyone know what to do? I've tried some other Insert commands, but nothing wants to work.
You have to associate a connection with your command then execute your query:
InsertCommand.Connection = conn;
InsertCommand.ExecuteNonQuery();
Few other things:
Do not use string concatenation to create SQL Query. Use parameters with your query. See: SqlCommand.Parameters otherwise you are prone to SQL Injection
Enclose your connection and command object in using statement.
add the connection to your command and execute it:
SqlCommand InsertCommand = new SqlCommand("INSERT INTO invmgmt.Products (product_id, product_name, product_price, possible_discount, product_in_stock) VALUES ('" + Convert.ToInt32(tbAddProdID.Text) + "','" + tbAddProdName.Text + "','" + Convert.ToDouble(tbAddProdPrice.Text) + "','" + Convert.ToInt32(tbAddPblDiscount.Text) + "','" + Convert.ToInt32(tbAddInStock.Text) + "')",myConn);
InsertCommand.ExecuteNonQuery();
You are missing:
InsertCommand.ExecuteNonQuery();
after opening connection try code below:
string query = ..........;
SqlCommand myCommand = new SqlCommand(query, myConn);
myCommand.ExecuteNonQuery();
myConn.Close();
Note: type your query instead of dots.
ExecuteNonQuery() return the number of rows affected, so its better to check the return to handle error condition
Int32 ret = sqlcommand.ExecuteNonQuery();
if (ret <= 0)
{
enter code here
}
You have to execute the query and close your connection after this as shown below
SqlConnection myConn = new SqlConnection(myConnection);
myConn.Open();
string sql ="YOUR QUERY...";
SqlConnection myConn = new SqlConnection(myConnection);
myConn.Open();
SqlCommand InsertCommand = new SqlCommand(sql,myConn);
InsertCommand.ExecuteNonQuery();
myConn.Close();
or if you want to check if query is executed or not do this instead.
if(InsertCommand.ExecuteNonQuery()>0){ //some message or function }
the returned value are the number of rows affected by the statement.

Error SQL INSERT INTO with Odbc Command C#

Scenario:
I want to input data from textbox into the database based on microsoft data base (.mdb)
I already searching and find good clue and my result was here.
This Code below was inside command button click event:
using (OdbcConnection conn= new OdbcConnection())
{
conn.ConnectionString = #"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=C:\\BlaBlaBla.mdb;Uid=Admin;Pwd=;";
conn.Open();
using (OdbcCommand cmd = new OdbcCommand(
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
And when I click the command button, I get unfriendly exception
ERROR [42S02] [Microsoft][ODBC Microsoft Access Driver] Could not find
output table 'TABLENAME'.
That happened when I insert cmd.ExecuteNonQuery. If I didn't insert that, of course nothing happens in my table target.
So what mistakes did I make in that code? What should I do?
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", myConnection))
change this into
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", Conn))
you define Conn as your connection string not "myConnection"
So i changed to OleDbConnection And My Problem Cleared,
using (OleDbConnectionconn= new OleDbConnection())
{
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\LOSERONE\Documents\DATABASE\Latihan1.mdb";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand (
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
Seems, to connected the database must same as the connection string in the properties on the targeted database.
Does anyone can tell me what is the difference OleDbConnection with OdbcConnection in .mdb database file?!
This problem is because sql connection's default database after login is not the same where your table 'TABLENAME' exists. Try to add database name before table like this:
INSERT INTO DBNAME..TABLENAME (FIELD1, FIELD2)
replace your myConnection to Conn

ExecuteNonQuery: Connection property has not been initialized?

I get an error in my code:
ExecuteNonQuery: Connection property has not been initialized.
This could be due to the line in this code:
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')");
Full code:
{
string theUserId = Session["UserID"].ToString();
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
}
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
//FileUploadControl.SaveAs(Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
FileUploadControl.SaveAs(Path.Combine(fileuploadpath, filename));
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')");
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
There is another problem, I dont think its an insert I want as this is going to make a duplicate entry within my database, would it just be a case of changing it from INSERT INTO to UPDATE?
Also is there a way to overwrite upon uploading the image? Atm it just saving the image into the same folder as the one I already have? The first image or any image obviously isnt going to have the same file name so how would I go about overwriting any image in the folder with the one im uploading?
EDIT:
New error (fileupload works as its stored in the correct area but passing the fileupload to the insert statement is abit wonky)
I get the error
The file could not be uploaded. The following error occured: ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.5.9]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 ''C:\Users\Garrith\Documents\Visual Studio 2010\WebSites\WebSite1\userdata\1\uplo' at line 1
Which is kind of strange?
All im trying to do is save the filepath+filename in mydb my attempt at passing to the insert has obviously failed.
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
string filename = Path.GetFileName(FileUploadControl.FileName);
//FileUploadControl.SaveAs(Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/") + filename);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId + "/uploadedimage/");
FileUploadControl.SaveAs(Path.Combine(fileuploadpath, filename));
StatusLabel.Text = "Upload status: File uploaded!";
//some kind of function to take the path then enter it into my insert syntax?
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
As you can see on this line:
VALUES ('" + theUserId + "' , '" + fileuploadpath + "')", cn);
im missing the "filename" i tryed this:
VALUES ('" + theUserId + "' , '" + fileuploadpath, filename + "')", cn);
Cheap shot lol but worth a go I guess and it cryed as it always does!
You need to associate the connection with the cmd:
OdbcCommand cmd =
new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')");
cmd.Connection = cn; // <--------
cmd.ExecuteNonQuery();
Also, remove the braces here:
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};
Server=localhost; Database=gymwebsite2; User=root; Password=commando;"); cn.Open();
}
You want to create the OdbcCommand using CreateCommand on OdbcConnection. The code as posted does not tie cmd to cn. Also, you should use CommandParameters instead of inlining the values (to guard against SQL injection attacks).
OdbcCommand cmd = cn.CreateCommand();
cmd.CommandText = "INSERT INTO Pictures (UserID, picturepath) VALUES (?, ?)";
cmd.Parameters.Add(new OdbcParameter("#UserID", OdbcType.Int, theUserID));
cmd.Parameters.Add(new OdbcParameter("#picturepath", OdbcType.VarChar, fileuploadpath));
cmd.ExecuteNonQuery();
This is the problem:
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileuploadpath + "')"); <--- there is no connection intialize here
Change it to:
//eg: odbconnection cn = new odbcconnection();
string fileup = fileupload + "," filename;
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "' , '" + fileup.ToString() + "')",cn);
Regards
The following is syntactically fubar'd:
string theUserId = Session["UserID"].ToString();
{
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=root; Password=commando;");
cn.Open();
}

Categories