insert into database - c#

I've made sure everything pertains to the column types in the database, but I keep getting an SQLCeException. Can anyone tell me what's wrong with this code?
private void ANDPaddDriverButton_Click(object sender, EventArgs e)
{
string first = ANDPfirstNametextBox.Text;
string last = ANDPlastNametextBox.Text;
string mid = textBox5.Text;
string phone = ANDPphonetextBox.Text;
string social = ANDPsSNtextBox.Text;
// EmployeeType="Employee"
string city = ANDPCityTextbox.Text;
string state = ANDPStatetextBox.Text;
string zip = ANDPzipCodetextbox.Text;
string email = ANDPemailtextBox.Text;
string address = ANDPaddressTextBox.Text;
string user = userName.Text;
DBConn.Open();
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO [Employee Table] VALUES (" +
first + "," + last + "," + mid + "," + address + "," + phone + "," + social + ","
+ "Employee" + "," + city + "," + state + "," + zip + "," + email + "," + userName + ")", DBConn);
cmd.ExecuteNonQuery();
DBConn.Close();
}

Use Parameters to prevent SQL injection, and the Columns names, because you are relying in the quantity, and order of your table's columns and it will likely change in the future (I'm guessing the column names):
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO [Employee Table] (First, Last, Mid, Address, Phone, Social, Employee, City, State, Zip, Email, UserName) VALUES (#First, #Last, #Mid, #Address, #Phone, #Social, #Employee, #City, #State, #Zip, #Email, #UserName)", DBConn);
cmd.Parameters.AddWithValue("#First", first);
cmd.Parameters.AddWithValue("#Last", last);
cmd.Parameters.AddWithValue("#Mid", mid);
cmd.Parameters.AddWithValue("#Address", address);
cmd.Parameters.AddWithValue("#Phone", phone);
// etc. each column
By the way try to not use spaces in table and columns names ;-)

Your fields of type string/varchar shall be enclosed in single quotes!
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO [Employee Table] VALUES (" +
"'" + first + "',"
and so on...
Also, as somebody else already commented you're going to greatly expose your code to SQL injection attacks

As Lorenzo said, the string values must be enclosed with single quotes, but please read this page which explains why you shouldn't build a query this way, and shows you how to do it with parameters.

Related

problem inserting data into database using sql command

I have received the following error:
Syntax error in INSERT INTO statement.
I don't seem to be able to find the mistake. here is the code:
if (Request["su"] == "save")
{
string sqlCommand = "";
string fileName = "UsersDB.accdb";
string tableName = "Table 2";
string website_name, website_psw;
website_name = Request["psw_name"];
website_psw = Request["psw"];
sqlCommand = "INSERT INTO " + tableName + " (fname, lname, umail, upassword, gender, age, uid) ";
sqlCommand += "VALUES ('"+0+ "','" + Session["umail"].ToString() + "','" + website_psw + "','" + website_name + "')";
MyAdoHelper.DoQuery(fileName, sqlCommand);
}
As for the database, it has 4 rows:
uid, uidd, psw_name, psw
What is the issue in the code which leads to such error?
It looks like your INSERT statement is specifying 7 columns (fname, lname, umail, upassword, gender, age, uid) to insert into and only 4 columns of data.
The table name with a space in it is also likely to cause an issue. Enclosing it in square brackets should fix that issue.
You SQL should start like this (if this text: " it has 4 rows: uid, uidd, psw_name, psw" means your table has 4 columns):
INSERT INTO [Table 2] (uid, uidd, psw_name, psw) VALUES (...
Try this two lines :
sqlCommand = "INSERT INTO " + tableName + " (fname, lname, umail, upassword, gender,
age, uid) ";
sqlCommand += "VALUES (\'"+0+ "\',\'" + Session["umail"].ToString() + "\',\'" +
website_psw + "\',\'" + website_name + "\')";

Error: There are more columns in the INSERT statement than values specified in the VALUES clause

I've checked my values but it still says that I do not have enough. I have one value that isn't in the insert-statement but it's an identity-value, so I guess I don't have to specify that in my code?!?!
Anyway here's the code:
string Fname = tbFIRSTNAME.Text.Trim();
string Lname = tbLASTNAME.Text.Trim();
string Sname = tbStreetName.Text.Trim();
string SSN = tbSSN.Text.Trim();
string CrimeID = cmbCRIMEID.Text.ToString();
string DangerLVL = cmbDANGERLEVEL.Text.ToString();
string CrimeDesc = rtbCrimeInfo.Text.Trim();
string str = "insert into Crooks (FirstName, LastName, StreetName, SSN, CrimeID, DangerLevel, CrimeDescription) values ('" + Fname + '"' + Lname + '"' + Sname + '"' + SSN + '"' + DangerLVL + '"' + CrimeID + '"' + CrimeDesc + "')";
clsDB.InsUpDel(str);
Your basic error, as others stated, is that you are not separating all the values with commas.
Apart from that, you have a big security flaw. And that is to use your values directly from your textboxes. That is the most insecure and most common security flaw in software design and will potentially lead you to have SQL Injection attacks to your application. To avoid that, you should use parametrized query. This is a resumed code, but you should so something like this:
using(MySqlConnection conn = new MySqlConnection("YourConnectionString"))
{
conn.Open();
MySqlCommand command = conn.CreateCommand();
command.CommandText = "insert into Crooks (FirstName, LastName, StreetName, SSN, CrimeID, DangerLevel, CrimeDescription) VALUES (#FirstName, #LastName, #StreetName, #SSN, #CrimeID, #DangerLevel, #CrimeDescription)";
command.Parameters.AddWithValue("#FirstName", tbLASTNAME.Text.Trim());
command.Parameters.AddWithValue("#LastName", tbStreetName.Text.Trim());
/*
...
AND SO ON WITH OTHER PARAMETERS
...
*/
command.ExecuteNonQuery();
conn.Close();
}
The problem is that you haven't set comma between your values (So you are actually entering one value not 7):
string str = "insert into Crooks (FirstName, LastName, StreetName, SSN, CrimeID, DangerLevel, CrimeDescription) values ('" + Fname + "','" + Lname + "','" + Sname + "'," + SSN + "," + DangerLVL + "," + CrimeID + ",'" + CrimeDesc + "')";
Clearly some of varchar types are not enclosed between '' too. this is not the case right now, but after adding commas you may get other errors because of type mismatches

I am getting 'System.Web.UI.WebControls.TextBox' into sql table instead of getting actual data entered in text boxes

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 + "')";

Number of query values and destination fields are not the same error

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

C# syntax error in INSERT INTO statement

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();

Categories

Resources