Using Access database like this :
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Request.PhysicalApplicationPath + "Resources/cars_db.accdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO Users (Username, Password, Email, Address, Question, Answer) VALUES ('" + txtUsernameRP.Text + "','" + txtPasswordRP.Text + "','" + txtEmailRP.Text + "','" + txtAddressRP.Text + "','" + txtQuestionRP.Text + "','" + txtAnswerRP.Text + "')";
int i = cmd.ExecuteNonQuery(); -- **Breaks here and says syntax error**
I have tried:
Taking out the int i bit.
Putting the # symbol in front of the statement.
Checked and made sure that I am using the Access code.
Tried closing the connection before creating in case it was something there.
Substituted the data for fixed values, which I then ran in a query in Access which worked.
Put the access query mentioned above into the code block (cmd.CommandText = "INSERT INTO Users (Username, Password, Email, Address, Question, Answer) VALUES ('asdasd','Asd!23asd','asdasd','asdasd','asdasd','asdasd')"; and tried running it and again same syntax error.
Please someone help me...
Password is reserved keyword
cmd.CommandText = "INSERT INTO Users (Username, Password, Email, Address...
try this
cmd.CommandText = "INSERT INTO Users (Username, [Password], Email, Address...
Can You try this?
"INSERT INTO Users (Username, Password, Email, Address, Question, Answer)
VALUES(
'" + txtUsernameRP.Text + "',
'" + txtPasswordRP.Text + "',
'" + txtEmailRP.Text + "',
'" + txtAddressRP.Text + "',
'" + txtQuestionRP.Text + "',
'" + txtAnswerRP.Text + "');";
I guess your problem is on that int i, try removing it
Related
I am trying to insert a row in my User table (SQL Server Compact 3.5). This is my query (LastName, FirstName and UserPassword are NVARCHAR, IsActive is BIT):
INSERT INTO Users (LastName, FirstName, IsActive, UserPassword) VALUES ('J', 'R', 1, 'T')
I converted this to the following code block in C#:
string returnQuery = "INSERT INTO Users (LastName, FirstName, IsActive, UserPassword)"
+ "VALUES(" + "'" + "#LastName" + "', '" + "#FirstName" + "', #IsActive" + ",'" + "#UserPassword" + "'";
SqlCeCommand returnQueryCommand =
new SqlCeCommand(returnQuery, connection) { CommandType = CommandType.Text };
returnQueryCommand.Parameters.AddWithValue("#LastName", newUser.LastName);
returnQueryCommand.Parameters.AddWithValue("#FirstName", newUser.FirstName);
returnQueryCommand.Parameters.AddWithValue("#IsActive", newUser.IsActive);
returnQueryCommand.Parameters.AddWithValue("#UserPassword", newUser.UserPassword);
I get a parsing error when running my code. However, when I run the query straight through CompactView, the row gets inserted just fine.
I am executed the query in another method (I am returning SqlCeCommand from this method).
Thoughts?
missing close bracket after values
your given code seems to be missing a closing parenthesis to close "VALUES" data.
string returnQuery = "INSERT INTO Users (LastName, FirstName, IsActive, UserPassword)" + "VALUES(" + "'" + "#LastName" + "', '" + "#FirstName" + "', #IsActive" + ",'" + "#UserPassword" + "')";
Can someone please help me figure out why I am getting 'System.Web.UI.WebControls.TextBox' in MySQL database instead of actual values being entered in the text field. The code I am using is below ..
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
string queryStr;
string connString=System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnectionString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "INSERT INTO seework.userdata (First_Name, Middle_Name, Last_Name, Email_Address, Phone_Number, Username, Password)" + "VALUES('" + firstnameTextBox + "','" + middlenameTextBox + "','" + lastnameTextBox + "','" + emailaddressTextBox + "','" + phonenoTextBox + "','" + usernameTextBox + "','" + passwordTextBox + "')";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
conn.Close();
I have tried all I could but still no luck. Any help would be really appreciated.
Thanks in Advance!
You are passing the TextBox itself to the database using the query. You need to pass the text instead. For this you can use .Text property of the TextBox control. Which gives you the Text/Content inside the Textbox Control. And one more advise for you. Use Parameterized queries instead for cuch queries to avoid Sql Injection.
For example:
queryStr = "INSERT INTO seework.userdata (First_Name, Middle_Name)VALUES(#fName,#mName)";
SqlCommand cmd = new SqlCommand(queryStr);
cmd.Parameters.Add("#fName",SqlDbType.VarChar).Value=firstnameTextBox.Text ;
cmd.Parameters.Add("#mName",SqlDbType.VarChar).Value=middlenameTextBox.Text;
// Build your command like this
// Execute the command then
you should use .Text after the name of TEXTBOX.
For Example :-
string insert = "insert into table_Name (Name, Contact, Email) values ('" + txtname.Text + "', '" + txtcontact.Text + "', '" + txtemail.Text + "')";
I'm getting the error:
Data type mismatch in criteria expression
When using this code. And using Access database.
OleDbConnection bab = new OleDbConnection();
bab.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\sdega\OneDrive\school\Werknemersdata.accdb;Persist Security Info=False;";
bab.Open();
try
{
OleDbCommand kaas = new OleDbCommand();
kaas.Connection = bab;
kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values ('" + txtNaam.Text + "', '" + txtAdress.Text + "', '" + txtpostcode1.Text + " " +txtpostcode2.Text + "', '" + txtwoonplaats.Text + "', '" + txtsalaris.Text + "') ";
kaas.ExecuteNonQuery(); // this is where it goes wrong
txtStatus.BackColor = Color.Green;
MessageBox.Show("data saved");
bab.Close();
}
catch (Exception ghakbal)
{
MessageBox.Show("Error" + ghakbal);
}
You missed one ' after '" + txtpostcode1.Text + " and one before " +txtpostcode2.Text + "' and also one , between them. It should be like this:
'" + txtpostcode1.Text + "' , '" +txtpostcode2.Text + "',
Also I strongly recommend that you always use parameterized queries to avoid SQL Injection. Like this:
kaas.CommandText = "insert into Werknemersdata (Naam, Adres, Postcode, Woonplaats, Salaris) values (?, ? ,.....");
kaas.Parameters.AddWithValue("Naam", txtNaam.Text);
kaas.Parameters.AddWithValue("Adres", txtAdress.Text);
//And other parameters...
Also It would be better to specify the type directly and use the Value property. Read more here.
I am getting an error while inserting data into a database.
The error is:
"Number of query values and destination fields are not the same".
Insert code:
OleDbConnection vconn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Mutyyba\\Documents\\Database1.accdb");
vconn.Open();
string name = textBox1.Text;
string address = textBox3.Text;
int rollno = Convert.ToInt32(textBox2.Text);
string vquery = "insert into Table1 values(#vname,#vrollno,#vaddress)";
OleDbCommand vcomm = new OleDbCommand(vquery, vconn);
vcomm.Parameters.AddWithValue("#vname", name);
vcomm.Parameters.AddWithValue("#vrollno", rollno);
vcomm.Parameters.AddWithValue("#vaddress", address);
vcomm.ExecuteNonQuery();
MessageBox.Show("your record has been recorded sucessfully!");
vconn.Close();
What am I doing wrong?
I think you just missed some single quotes . I see you have enclosed all the parameters with a starting and end single quotes . See this
One more thing , as you are passing lot of parameter prepare a SqlCommand Object for Parameters.
See msdn for more details.
Do something like this :
SqlCommand comm = new SqlCommand("INSERT INTO table VALUES (#txtsno, #txtdesg, #txtbasic)", connection);
comm.Parameters.AddWithValue("#txtsno", txtsno.Text.Trim());
comm.Parameters.AddWithValue("#txtsno", txtdesg.Text.Trim());
comm.Parameters.AddWithValue("#txtsno", txtbasic.Text.Trim());
This would be more clearer and would not be prone of SQL Injection.
Try to use parameters to build the command
// Create the InsertCommand.
command = new OleDbCommand(
"INSERT INTO Customers (CustomerID, CompanyName) " +
"VALUES (?, ?)", connection);
// add parameters like below
command.Parameters.Add(
"CustomerID", OleDbType.Char, 5, "CustomerID");
command.Parameters.Add(
"CompanyName", OleDbType.VarChar, 40, "CompanyName");
You need to specify the column names in your SQL, or the value sequence should be the exact same (number and order) with the default schema of the table
OleDbCommand cmd = new OleDbCommand("insert into real (name, symbol, date, red, redby, redsell, sbintrabuy, sbtr1, sbtr2, sbtr3, sbintersell, sbtr1, sbtr2, sbtr3, rstl, green) values('" + Name + "','" + Symbol + "','" + Date + "','" + Red + "','" + RedBuy + "','" + RedSell + "','" + SBIntraBuy + "','" + SBTR1 + "','" + SBTR2 + "','" + SBTR3 + "','" + SBIntraSell + "','" + SBTR1 + "','" + SBTR2 + "','" + SBTR3 + "','" + RSTL + "','" + Green + "');", con);
Replace the bold columns with correct names, it's recommended that to specify the column names explictly.
The string values should be around with single quota
Normally, you should write sql like this:
cmd.Parameters.Add("var", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["var"].Value = 'somevalue';
In your sql should be like: "insert into real(column1) values(#var)".
====
I updated the answer as above, hope it can solve your problem.
insert into Main values (28494,1,False,'Buto-asma Sirop' , 'Buto-asma Sirop', 3.99 , 'Syrup', 'ispani', ' ', ' ',0, '1',4988 )
solves this problem
I'm having the error at the line: ins.ExecuteNonQuery().ToString(); OledDbException was unhandled Syntax error in INSERT INTO statement.
How do I fix this?
string strOleDbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Project.mdb";
OleDbConnection objConnection = new OleDbConnection(strOleDbConnectionString);
string newTagID = textBox1.Text;
string newUser = textBox2.Text;
string newAge = textBox3.Text;
string newPhoneNumber = textBox4.Text;
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES ('" + newTagID + "', '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Connection.Open();
ins.ExecuteNonQuery().ToString();
ins.Connection.Close();
Your problem is probably one these three:
Outright syntax error not clearly visible with the hideous unparametrized SQL statement :p
newUser or some other field has a ' somewhere and is screwing up the syntax.
You are trying to insert a numeric value (Age?) as a string.
You should easily solve the first two creating a breakpoint after the insertString statement construction and checking out what the string really contains. The third one is even easier to check, just review the data types of the table's fields in your data base.
Notwithstanding, you should change the use of your command to use parameters and not build the query string with string concatenation (which is susceptible to sql injection attacks).
The issue is most likely because [Tag ID], User, Age, [Phone Number] are not all strings. In your SQL, any non-string column data should not be wrapped by quotes (').
To fix the immediate problem (assuming [Tag ID] is an integer):
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (" + newTagID + ", '" + newUser + "', '" + newAge + "', '" + newPhoneNumber + "')";
However, you should structure your code to avoid sql injection, have cleaner code, and also not worry about the quotes:
string insertString = "INSERT INTO jiahe ([Tag ID], User, Age, [Phone Number]) VALUES (#TagID, #User, #Age, #PhoneNumber)";
OleDbCommand ins = new OleDbCommand(insertString, objConnection);
ins.Parameters.Add(new OleDbParameter("#TagID",newTagID);
ins.Parameters.Add(new OleDbParameter("#User",newUser);
ins.Parameters.Add(new OleDbParameter("#Age",newAge);
ins.Parameters.Add(new OleDbParameter("#PhoneNumber",newPhoneNumber);
ins.Connection.Open();
ins.ExecuteNonQuery();
ins.Connection.Close();