Error in MySQL synax inserting new data c# - c#

I think its one of those question where you need a second pair of eyes to have a look at.
I trying to add new record and just keep getting same error which is "Error in SQL syntax , I am using MySQL and here is the table
script for MySQL
create table tbl_employee(
employeeID smallint,
employee_Fname varchar(30),
employee_Sname varchar(30),
employee_AddressL1 varchar(100),
employee_AddressL2 varchar(100),
employee_PostCode varchar(10),
employee_tel_type enum('work', 'mobile', 'personal'),
employee_Image varchar(250),
employee_Job_Role enum('admin','accounts','management','maintiantance','Sales'),
employee_Salary float,
employee_imagePath varchar(250),
employee_tel_no varchar(100),
Primary key(employeeID)
);
and here is the C# code
connected = DataConnection.getConn();
MySqlCommand cmd = new MySqlCommand("", connected); //
//This is my insert query in which i am taking input from the user through windows forms
//insert into tbl_employee value (2,'John','Rafiq','234 Zoo Rd','Alcala','2388','work' ,'admin',3500.89,'C:\blindXimages','111-111' );
string Query = "Insert into tbl_employee (employeeID,employee_fname,employee_Sname,employee_AddressL1,employee_AddressL2,employee_PostCode, employee_tel_type,employee_Job_Role,employee_Salary,employee_ImagePath,employee_tel_no)" +
"'value('" + Convert.ToInt32( this.txtEmployeeID.Text) + "'," + this.txtName.Text + "','" + this.txtSurname.Text + "','" + this.txtAddressL1.Text + "','" + this.txtAddressL2.Text + "','" + this.txtPostCode.Text + "','" + this.txtTelType.Text + "','" + this.txtJobRole.Text + "','" + Convert.ToDecimal( this.txtSalary.Text) + "','" + this.txtFaceName.Text + "','" + this.txtTelephoneNo.Text + "')";
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query, connected);
MySqlDataReader MyReader2;
MyReader2 = MyCommand2.ExecuteReader(); // Here our query will be executed and data saved into the database.
MessageBox.Show("Save Data");
while (MyReader2.Read())
{
}
// connected.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
btnAddNew.Enabled = false;
MessageBox.Show("Data is save clearing all text boxes ");
clearTextBox();
}
I have double and triple check my syntax just can't figure out were I am going wrong line by line. will very much appropriate this support.

use "values" instead of "value" and add space before values.

Related

Query doesn't store my registration form data asp.net

I actually new in asp.net c# I want to know why this code below doesn't work.
All I want to do is store data form into a SQL Server database.
I have 2 tables and I want the data form entered stored in the database. Look at the select statement for retrieving the primary key to store it as a foreign key in the other table
String q = "Insert into dbo.requests(request_date,request_type,visit_date,reason,user_id,status_id)values('" + DateTime.Now.ToString() + "','" + DropDownList1.SelectedValue.ToString() + "','" + TextBox8.Text.ToString() + "','" + TextBox9.Text.ToString() + "','"+ 1+"','"+ 2+"')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
con.Close();
con2.Open();
if (con2.State == System.Data.ConnectionState.Open)
{
String a = "select top 1 request_id from dbo.requests where request_date= CAST(GETDATE() AS DATE and user_id=999 order by request_id DESC ";
SqlCommand cmd2 = new SqlCommand(a, con2);
int r = cmd2.ExecuteNonQuery();
}
con2.Close();
con3.Open();
if (con3.State == System.Data.ConnectionState.Open)
{
String b = "INSERT into dbo.visitor(visitor_Fname,visitor_Mname,visitor_family_name,visitor_id,visitor_mobile,request_id,place_of_work,country_name) values ('" + TextBox1.Text.ToString() + "','" + TextBox2.Text.ToString() + "','" + TextBox3.Text.ToString() + "','" + TextBox4.Text.ToString() + "' , '" + TextBox5.Text.ToString() + "','r', '" + TextBox6.Text.ToString() + "', '" + TextBox7.Text.ToString() + "' )";
SqlCommand cmd3 = new SqlCommand(b, con3);
cmd3.ExecuteNonQuery();
}
You should change it
int r = cmd2.ExecuteNonQuery();
to
int r = (int)cmd2.ExecuteScalar();
To retrieve selecting only one field use ExecuteScalar instead of ExecuteNonQuery. ExecuteNonQuery doesn't return selecting fields.
Just store request_id in variable using data table.
Actually you are storing 'r' in table which is wrong. Try to store request_id from select statement in variable it will be work .

Inserting into two tables with one query

What's wrong with my code, i tried to combine two query into one. But the second query is not working, i already follow the answer of this link INSERT INTO two tables at one query but i think mine doesn't work, am i missing something in my code?
string sql = "INSERT INTO tbladdbook(fBookTitle,fAuthor,fBookYr,fEdition,fPublication,fAccNo,fCallNo,fCategory,fBarCodeNo,fCurrentCopies) VALUES('"
+ txtTITLE.Text + "','"
+ txTAUTHOR.Text + "','"
+ txtBOOKYR.Text + "','"
+ txtEDITION.Text + "','"
+ txtPUBLICATION.Text + "','"
+ txtACCESSNO.Text + "','"
+ txtCALLNO.Text + "','"
+ txtCATEGORY.SelectedItem + "','"
+ txtBARCODE.Text + "','"
+ txtCOPIES.Text + "'); INSERT INTO tbltruecopies(fBookTitle,fAuthor,fBarCodeNo,fTrueCopies) VALUES('"
+ txtTITLE.Text + "','"
+ txTAUTHOR.Text + "','"
+ txtBARCODE.Text + "','"
+ txtCOPIES.Text + "')";
cfgotcall.inputQ(sql);
Table definition: for tbladdbook
fBookTitle varchar
fAuthor varchar
fEdition varchar
fBookYr varchar
fPublication varchar
fAccNo varchar
fCallNo varchar
fCategory varchar
fBarCodeNo varchar
fCurrentCopies float
Table definition: for tbltrue
fBookTitle varchar
fAuthor varchar
fBarCodeNo bigint
fTrueCopies bigint
Old and working code:
string sql = "INSERT INTO tbladdbook(fBookTitle,fAuthor,fBookYr,fEdition,fPublication,fAccNo,fCallNo,fCategory,fBarCodeNo,fCurrentCopies) VALUES('"
+ txtTITLE.Text + "','"
+ txTAUTHOR.Text + "','"
+ txtBOOKYR.Text + "','"
+ txtEDITION.Text + "','"
+ txtPUBLICATION.Text + "','"
+ txtACCESSNO.Text + "','"
+ txtCALLNO.Text + "','"
+ txtCATEGORY.SelectedItem + "','"
+ txtBARCODE.Text + "','"
+ txtCOPIES.Text + "')";
cfgotcall.inputQ(sql);
sql = "INSERT INTO tbltruecopies(fBookTitle,fAuthor,fBarCodeNo,fTrueCopies) VALUES('"
+ txtTITLE.Text + "','"
+ txTAUTHOR.Text + "','"
+ txtBARCODE.Text + "','"
+ txtCOPIES.Text + "')";
cfgotcall.inputQ(sql);
Captain Teemo asked if I was able to rewrite using parameters.
This is a relatively easy operation; however, I write for SQL Server and there may be slight differences with the MySql commands and I do not the cfgotcall methods (is this Cold Fusion?) that are being used for the Data Layer, so I will just write this in ADO.
In this case I simply replaced all of the values in the VALUES clause with SQL Variables, and basically reused the column names with a preceding #, so the column fBookTitle is assigned the value #fBookTitle. Then we can assign those parameters to the command object via the Parameters.AddWithValue() method. For the above #fBookTitle value the call would be cmd.Parameters.AddWithValue("#Title", txtTITLE.Text); I noticed that the variables being used in the second query were all in the first query, but not vice versa; so I am going to build up execute Qry2 first, then we can simply change the CommandText and add in the additional parameters.
One of the things with using parameters is that you will need to add the values with the correct type, so adding in a value that is a BigInt in the database will need to be added in as the corresponding C# type of Int64.
What I can do is show how this would be done via ADO with SQL Server, and you can modify what needs to be done. If you can't find a cfgotcall that works with parameters then you could just change this for use with MySql which has nearly identical syntax to the SQL Server syntax.
string Qry1 = "INSERT INTO tbladdbook(fBookTitle,fAuthor,fBookYr,fEdition,fPublication,fAccNo,fCallNo,fCategory,fBarCodeNo,fCurrentCopies) VALUES (#Title, #Author, #BookYr, #Edition, #Publication, #AccNo, #CallNo, #Category, #BarCode, #Copies)";
string Qry2 = "INSERT INTO tbltruecopies(fBookTitle, fAuthor, fBarCodeNo, fTrueCopies) VALUES (#Title, #Author, #Barcode, #Copies)";
using (SqlConnection conn = new SqlConnection(connectionstring)) {
conn.Open();
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = Qry2;
cmd.Parameters.AddWithValue("#Title", txtTITLE.Text);
cmd.Parameters.AddWithValue("#Author", txTAUTHOR.Text);
cmd.Parameters.AddWithValue("#Barcode", Int64.parse(txtBARCODE.Text));
cmd.Parameters.AddWithValue("#Copies", Int64.parse(txtCOPIES.Text));
try { cmd.ExecuteNonQuery(); }
catch (Exception) { /* your error handling */ }
cmd.CommandText = Qry1;
cmd.Parameters.AddWithValue("#BookYr", txtBOOKYR.Text);
cmd.Parameters.AddWithValue("#Edition", txtEDITION.Text);
cmd.Parameters.AddWithValue("#Publication", txtPUBLICATION.Text);
cmd.Parameters.AddWithValue("#AccNo", txtACCESSNO.Text);
cmd.Parameters.AddWithValue("#CallNo", txtCALLNO.Text);
cmd.Parameters.AddWithValue("#Category", txtCATEGORY.SelectedItem);
try { cmd.ExecuteNonQuery(); }
catch (Exception) { /* your error handling */ }
}
conn.Close();
}
Tetsuya Yamamoto suggests that this be converted over to a Stored Procedure
This is an easy enough task on SQL Server, but I do not know the MySql implementation; sorry you are going to get what I would be typing in Query Analyzer or SSMS, and this would most likely to be translated for MySql as well.
The syntax for this procedure is going to be rather simple, as all we are going to do is wrap the 2 queries within it.
CREATE PROCEDURE usp_addBookAndCopies (
#Title VARCHAR(100),
#Author VARCHAR(100),
#BookYr VARCHAR(100),
#Edition VARCHAR(100),
#Publication VARCHAR(100),
#AccNo VARCHAR(100),
#CallNo VARCHAR(100),
#Category VARCHAR(100),
#BarCode BIGINT,
#Copies BIGINT
) AS
BEGIN
INSERT tbladdbook ( fBookTitle, fAuthor, fBookYr, fEdition, fPublication,
fAccNo, fCallNo, fCategory, fBarCodeNo, fCurrentCopies )
VALUES (#Title, #Author, #BookYr, #Edition, #Publication,
#AccNo, #CallNo, #Category, #BarCode, #Copies )
INSERT tbltruecopies ( fBookTitle, fAuthor, fBarCodeNo, fTrueCopies)
VALUES (#Title, #Author, #Barcode, #Copies)
END
GO
Once we have the Stored Procedure created, we would need to modify the original code, removing the 2 INSERT queries and replace them with the one command calling the procedure. We would also change the command type to reflect that we are running a procedure instead of a text command.
// Not Needed: string Qry1 = "INSERT INTO tbladdbook..."
// Not Needed: string Qry2 = "INSERT INTO tbltruecopies..."
using (SqlConnection conn = new SqlConnection(connectionstring)) {
conn.Open();
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure; // Changed
cmd.CommandText = "usp_addBookAndCopies"; // Changed
cmd.Parameters.AddWithValue("#Title", txtTITLE.Text);
cmd.Parameters.AddWithValue("#Author", txTAUTHOR.Text);
cmd.Parameters.AddWithValue("#Barcode", Int64.parse(txtBARCODE.Text));
cmd.Parameters.AddWithValue("#Copies", Int64.parse(txtCOPIES.Text));
cmd.Parameters.AddWithValue("#BookYr", txtBOOKYR.Text);
cmd.Parameters.AddWithValue("#Edition", txtEDITION.Text);
cmd.Parameters.AddWithValue("#Publication", txtPUBLICATION.Text);
cmd.Parameters.AddWithValue("#AccNo", txtACCESSNO.Text);
cmd.Parameters.AddWithValue("#CallNo", txtCALLNO.Text);
cmd.Parameters.AddWithValue("#Category", txtCATEGORY.SelectedItem);
try { cmd.ExecuteNonQuery(); }
catch (Exception) { /* your error handling */ }
}
conn.Close();
}
My Comments
Looking at the actual statements and the code this appears to be adding books to a library of sorts. There is a table of Books (tbladdbook) and another for Book Copies (tbltruecopies), and the only thing different between the two tables is that Copies would reflect how many copies are currently on hand, but the Count is of dissimilar types; one being Float and the other as BigInt. My opinion would be that these two should be of the same type, and I really don't think it is realistic that these values would ever exceed the capacity of a 32 bit integer, if not 16 bit. Not too mention that Float and Double are only approximations.
This a rather long answer, and my aging eyes may have a syntax error or two. Please forgive me and let me know of any errors or suggestions, I will be happy to update this for you.

using windows form c# to add values to Mysql database

I need to get the userid(primary key auto_increment) from another table(login) into userdetails table. When trying to run it I keep getting this error " incorrect integer value: 'LAST_INSERT_ID()' for column 'userid' at row 1".
I've tried to take LAST_INSERT_ID() out and run another query after query4 to insert the value into the userid but I can't get it to insert into the right row it just opens a new row.
this is the code am trying to run.
try
{
//This is my connection string i have assigned the database file address path
string MyConnection2 = "datasource=localhost;port=3310;database=e-votingsystem;username=root;password=Password12;";
//this is my insert query in which i am taking input from the user through windows forms
string Query2 = "INSERT INTO vote (username) VALUE ('" + usernameInputBox.Text + "');";
string Query3 = "INSERT INTO login (username,upassword) VALUE ('" + usernameInputBox.Text + "','" + passwordInputBox.Text + "');";
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUES ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text+"');";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query2, MyConn2);
MySqlCommand MyCommand3 = new MySqlCommand(Query3, MyConn2);
MySqlCommand MyCommand4 = new MySqlCommand(Query4, MyConn2);
MySqlDataReader MyReader2;
MySqlDataReader MyReader3;
MySqlDataReader MyReader4;
// opens new connection to database then executes command
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader(); // Here the query will be executed and data saved into the database.
while (MyReader2.Read())
{
}
MyConn2.Close();
// opens new connection to database then executes command
MyConn2.Open();
MyReader3 = MyCommand3.ExecuteReader();
while (MyReader3.Read())
{
}
MyConn2.Close();
//opens new connection to database the exexcutes command
MyConn2.Open();
MyReader4 = MyCommand4.ExecuteReader();
while (MyReader4.Read())
{
}
MyConn2.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
MessageBox.Show("Hello " + forename + surname, "read and accept the terms and conditions to continue");
//new termsAndConditionsPage().Show();
//Hide();
}
As explained in other answer, you have the LAST_INSERT_ID between single quotes and this transform it in a literal string not in a statement to execute. However also removing the quotes I am not sure that you can retrieve the LAST_INSERT_ID using a connection different from the one that originates the AUTOINCREMENT number on the login table. In any case you should use a different approach and, as a first thing, you should remove ASAP the string concatenations and use parameters (Reason: Sql Injection or SurName = O'Neill)
string Query2 = "INSERT INTO vote (username) VALUE (#uname)";
string Query3 = #"INSERT INTO login (username,upassword) VALUE (#uname, #upass);
SELECT LAST_INSERT_ID();";
string Query4 = #"INSERT INTO userdetails
(nationalinsurance,userid,forename,middlename,
surname,housenumber,street,towncity,postcode,suffix)
VALUES (#insurance, #userid, #forename, #middlename,
#surname, #housenum, #street, #town, #postcode, #suffix)";
Now open just one connection and build three commands, all between an using statement
using(MySqlConnection con = new MySqlConnection(.....constring here....))
using(MySqlCommand cmd2 = new MySqlCommand(Query2, con))
using(MySqlCommand cmd3 = new MySqlCommand(Query3, con))
using(MySqlCommand cmd4 = new MySqlCommand(Query4, con))
{
con.Open();
// Add the parameter to the first command
cmd2.Parameters.Add("#uname", MySqlDbType.VarChar).Value = usernameInputBox.Text;
// run the first command
cmd2.ExecuteNonQuery();
// Add parameters to the second command
cmd3.Parameters.Add("#uname", MySqlDbType.VarChar).Value = usernameInputBox.Text;
cmd3.Parameters.Add("#upass", MySqlDbType.VarChar).Value = passwordInputBox.Text;
// Run the second command, but this one
// contains two statement, the first inserts, the
// second returns the LAST_INSERT_ID on that table, we need to
// catch that single return
int userID = (int)cmd3.ExecuteScalar();
// Run the third command
// but first prepare the parameters
cmd4.Parameters.Add("#insurance", MySqlDbType.VarChar).Value = nationalInsuranceInputBox.Text;
cmd4.Parameters.Add("#userid", MySqlDbType.Int32).Value = userID;
.... and so on for all other parameters
.... using the appropriate MySqlDbType for the column type
cmd4.ExecuteNonQuery();
}
you current query has an error
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');SELECT LAST_INSERT_ID();"
try the attached query
In your text query string you have: "','"+"LAST_INSERT_ID()"+"','". Note that the "','"s before and after the "LAST_INSERT_ID()" are incorrectly enclosing the LAST_INSERT_ID() term in single quotes.
Try the following query:
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "',"+"LAST_INSERT_ID()"+",'" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');";

Insert Auto increment C# ... Error Cant be Null

I get the error that ID cant be Null, but it should auto increment
Using this code:
cn.Open();
cmd.CommandText = " insert into Firmen(Firmenname,UstID,Telefonnummer) Values('" + tbFName.Text + "','" + tbUstID.Text + "','" + tbTelF.Text + "')";
cmd.ExecuteNonQuery();
cn.Close();
I thought it would auto increment when I just Ignore the ID. Please help me

Copy table content to another table in the same database with C#

Copy table content to another table in the same database with C#.
I got one database (Baza) with some data in two tables NEW and OLD. I need to periodically move NEW data to OLD data table (after I do some measuring). I need to compare these data in next step.
I'm using SQL Server CE wit Baza.sdf file. In any sophisticated way to copy table to table do it (some loop doing it automatically)?
Thanks
I solved it in this way:
Program reads in loop table NEW row by row and each value changes to parameter. I got 8 columns so 8 parameters(7 integers and one string)
Next each of parameter is inserted to OLD table.
Resuld is also displayed in textBox1:
SqlCeConnection conn = new SqlCeConnection("Data Source = \\Program Files\\My Program\\Program.sdf; Password ='mypassword'");
conn.Open();
try
{
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [NEW]", conn);
SqlCeDataReader rdr = cmd.ExecuteReader();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
while (rdr.Read())
{
int param1 = rdr.GetInt32(0);
int param2 = rdr.GetInt32(1);
int param3 = rdr.GetInt32(2);
int param4 = rdr.GetInt32(3);
int param5 = rdr.GetInt32(4);
int param6 = rdr.GetInt32(5);
int param7 = rdr.GetInt32(6);
string param8 = rdr.GetString(7);
textBox1.AppendText(" " + param1 + " " + param2 + " " + param3 + " " + param4 + " " + param5 + " " + param6 + " " + param7 + " " + param8);
textBox1.AppendText(System.Environment.NewLine);
SqlCeCommand ins = new SqlCeCommand("insert into [OLD] values ('" + param1 + "','" + param2 + "','" + param3 + "','" + param4 + "','" + param5 + "','" + param6 + "','" + param7 + "','" + param8 + "');");
ins.Connection = conn;
ins.ExecuteNonQuery();
}
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
}
conn.Close();
What's wrong with:
insert into [table] (field1, field2)
select field1, field2 from [table2] where (your conditions are met)
? :-)
Since that's not supported in CE, thanks #marc_s, you could get the records from the NEW table using a select, then insert them into the OLD table, and then loop through the initial recordset to delete the rows from the NEW by ID for example.
Adding to what CodeCaster stated,
Put his code in a storedprocedure and create a job to run on a set interval of your choosing.
You can add logic to the storedprocedure to check the validity of the data as well and set it to notify you if the data was incorrect. Examples could be given if you included a more specific information in your question.

Categories