How do you insert into a table in a .sdf database?
I've tried the following:
string connection = #"Data Source=|DataDirectory|\InvoiceDatabase.sdf";
SqlCeConnection cn = new SqlCeConnection(connection);
try
{
cn.Open();
}
catch (SqlCeException ex)
{
MessageBox.Show("Connection failed");
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
string clientName = txt_ClientName.Text;
string address = txt_ClientAddress.Text;
string postcode = txt_postcode.Text;
string telNo = txt_TelNo.Text;
string sqlquery = ("INSERT INTO Client (Name,Address,Postcode,Telephone_Number)Values(" + clientName + "','" + address + "','" + postcode + "','" + telNo + ")");
SqlCeCommand cmd = new SqlCeCommand(sqlquery, cn);
try {
int affectedRows = cmd.ExecuteNonQuery();
if (affectedRows > 0)
{
txt_ClientAddress.Text = "";
txt_ClientName.Text = "";
txt_postcode.Text = "";
txt_TelNo.Text = "";
MessageBox.Show("Client: " + clientName + " added to database. WOoo");
}
}
catch(Exception){
MessageBox.Show("Insert Failed.");
}
But it doesn't seem to matter what i do it just shows "Insert Failed".
Thanks in advance.
You forgot opening quotation mark on the first value.
Values(" + clientName + "','"
change to:
Values('" + clientName + "','"
But this is generally a bad way to build query. Use parametrized query instead.
See: http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlcecommand.parameters(v=vs.80).aspx
catch(Exception ex)
{
MessageBox.Show(ex);
}
Will give you more info on error.
It is the same old story. When you build a sql command concatenating string these kinds of errors abund. And the simple syntax problem is not the worst. The Sql Injection is the most dangerous one.
Please build your query in this way
string sqlquery = ("INSERT INTO Client (Name,Address,Postcode,Telephone_Number)" +
"Values(#client,#address, #postcode, #tel)";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, cn);
cmd.Parameters.AddWithValue("#client", clientName);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#postcode", postcode);
cmd.Parameters.AddWithValue("#tel", telNo);
cmd.ExecuteNonQuery();
As others have already said your syntax error is caused by omitting the initial single quote. But you could have other errors. For example, what about a client called O'Hara?. Now you have a single quote inside the clientname and this wreak havoc your string concatenation.
Instead a parameter will be accurately parsed and every problematic character found will be treated appropriately (in this case doubling the single quote)
Your SQL statement is incorrect.
string sqlquery = ("INSERT INTO Client (Name,Address,Postcode,Telephone_Number)Values('" + clientName + "','" + address + "','" + postcode + "','" + telNo + "')");
Take this. You forgot the ' at the beginning and the end of the values
To insert data into Sql, data type should be considered. If you insert a string value (varchar) you have to surround it by single quotation, like '"+full_Name+"', but integer type doesn't need this. example
string myQuery = "INSERT INTO Persons (phone, fullname) VALUES ("+telNo+",'"+full_Name+"')";
where full name is string variable and phone number is only number.
Related
I have tried MANY suggested solutions from here but nothing seems to work for this problem. I just keep getting this error message when it hits the 'mdr = command.ExecuteReader();' line. Any thoughts please?
try
{
MySqlConnection connection = new MySqlConnection("SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";");
MySqlCommand command;
MySqlDataReader mdr;
connection.Open();
string ThePID = tbPID.Text;
string TheRound = tbRound.Text;
string CurrentPage = tbCurrentPage.Text;
// SELECT #myvar:= myvalue
string query = "SELECT ImageURL, ProofingText " +
"INTO #ImageURL, #ProofingText " +
"FROM Rounds " +
"WHERE ProjectID = " + ThePID + " " +
"AND CurrentRound = " + TheRound + " " +
"AND Page = " + CurrentPage + ";";
command = new MySqlCommand(query, connection);
mdr = command.ExecuteReader();
mdr.Read();
rtProofing.Text = mdr.GetString("#PRoofingText");
tbURL.Text = mdr.GetString("#ImageURL");
tbImagePage.Text = Path.GetFileName(tbURL.Text);
PageBox.Image = Image.FromFile(tbURL.Text);
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you use MySqlConnector, you will get a helpful exception message that explains the problem:
Parameter '#ImageURL' must be defined. To use this as a variable, set 'Allow User Variables=true' in the connection string.
By default, MySQL queries (executed from .NET) can't use user-defined variables. You can relax this limitation by adding Allow User Variables=true to your connection string.
However, this won't fix your underlying problem, which is that this isn't the right way to select data from MySQL.
Firstly, your query is susceptible to SQL injection; you should rewrite it to use parameters as follows:
using (var command = connection.CreateCommand())
{
command.CommandText = #"SELECT ImageURL, ProofingText
FROM Rounds
WHERE ProjectID = #ThePID
AND CurrentRound = #TheRound
AND Page = #CurrentPage;";
commands.Parameters.AddWithValue("#ThePID", ThePID);
commands.Parameters.AddWithValue("#TheRound", TheRound);
commands.Parameters.AddWithValue("#CurrentPage", CurrentPage);
Then, you can retrieve the values with a slight variation on your current code. You must retrieve the values by their column names, which do not have a leading #. You should also check that a row was retrieved by examining the return value of Read():
if (mdr.Read())
{
rtProofing.Text = mdr.GetString("ProofingText");
tbURL.Text = mdr.GetString("ImageURL");
}
Finally, string concatenation is also not the right way to build a connection string. The MySqlConnectionStringBuilder class exists for this purpose; use it.
var builder = new MySqlConnectionStringBuilder
{
Server = server,
Database = database,
UserID = uid,
Password = password,
};
using var connection = new MySqlConnection(csb.ConnectionString);
try
{
int i = 0;
using (SqlConnection sqlCon = new SqlConnection(Form1.connectionString))
{
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
// MessageBox.Show(commandString);
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
i = 1;
if (i == 0)
{
MessageBox.Show("Error in Logging In!", "Error");
}
MessageBox.Show("Successfully Logged In");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I'm making a LoginForm for a Project.I have created a table which shows the LoginDetails(Account,ID,LoginTime,LogoutTime).But when I run the Program,it doesn't runs successfully.I face an error which is in Pic-2.When I remove sql 'data reader',the program runs without displaying the error.
When you concatenate a null it basically adds nothing to the string, so this code:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
results of this string, and as you can see it has an extra comma, that causes the exception:
"INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('acc',textbxID,, SYSDATETIME());"
If you want to add NULL to the query it has to be a string, so do this instead:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID + ", NULL , SYSDATETIME()" + ");";
And you are using ExecuteReader instead of ExecuteNonQuery. You cannot use ExecuteReader for inserting rows to the DB.
Also, as someone mentioned in the other answer, you better do it with parametes to avoid SQL Injections.
Column name or number of supplied values does not match table definition. I'm not sure why.
public void saveToDB()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
con.Open();
string cmdtext = "Insert into tbl_user values ('" + txtname.Text + "','" + txtemail.Text + "','" + txtPassword.Text + "')";
SqlCommand cmd = new SqlCommand(cmdtext, con);
int no = cmd.ExecuteNonQuery();
if (no > 0)
{
SendEmail();
Response.Write("Register Succesfully");
}
else
{
Response.Write("Epic FAILED");
}
}
My database has:
name(varchar)
email(varchar)
password(varchar)
activated(bit)
For insert statements, if you dont insert into all the columns, (except Identity columns), you need to specify the column names, like so
string cmdtext = "Insert into tbl_user(name, email, password) values ('" + txtname.Text + "','" + txtemail.Text + "','" + txtPassword.Text + "')";
As per the comments, I neglected to let you know about best practices with SQL: check out how to prevent SQL Injection.
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 + "');";
I have declared the scalar already but I am still getting the error. My code checks to see if an entry exists, if it does it updates the entry or if it does not exist it creates a new entry:
try
{
string server = Properties.Settings.Default.SQLServer;
string connection = "Data Source=" + server + ";Initial Catalog=Propsys;Persist Security Info=True;User ID=sa;Password=0925greg";
using (SqlConnection cn = new SqlConnection(connection))
{
cn.Open();
SqlCommand cmdCount = new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #" + this.contactPersonTextBox.Text, cn);
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
SqlDataReader myReader;
myReader = cmdCount.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count > 0)
{
string query = "UPDATE _1Agent SET DealID = #DealID, \n" +
"ContactPerson = #ContactPerson, \n" +
"Address = #Address, \n" +
"TaxVatNo = #TaxVatNo, \n" +
"Comm = #Comm, \n" +
"WorkTel = #WorkTel, \n" +
"Cell = #Cell, \n" +
"Fax = #Fax, \n" +
"Email = #Email, \n" +
"Web = #Web, \n" +
"CreateDate = #CreateDate, \n" +
"Notes = #Notes WHERE id = #id";
SqlCommand cm = new SqlCommand(query);
string Contact = contactPersonTextBox.Text;
cm.Parameters.AddWithValue("#DealID", txtDealNo.Text);
cm.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
cm.Parameters.AddWithValue("#Address", addressTextBox.Text);
cm.Parameters.AddWithValue("#TaxVatNo", taxVatNoTextBox.Text);
cm.Parameters.AddWithValue("#Comm", commTextBox.Text);
cm.Parameters.AddWithValue("#WorkTel", workTelTextBox.Text);
cm.Parameters.AddWithValue("#Cell", cellTextBox.Text);
cm.Parameters.AddWithValue("#Fax", faxTextBox.Text);
cm.Parameters.AddWithValue("#Email", emailTextBox.Text);
cm.Parameters.AddWithValue("#CreateDate", DateTime.Now);
cm.Parameters.AddWithValue("#Notes", notesTextBox.Text);
cm.CommandText = query;
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Saved...", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
else
{
string query1 = "INSERT INTO _1Agent (DealID, \n" +
"ContactPerson, \n" +
"Address, \n" +
"TaxVatNo, \n" +
"Comm, \n" +
"WorkTel, \n" +
"Cell, \n" +
"Fax, \n" +
"Email, \n" +
"CreateDate, \n" +
"Notes) VALUES ('" + txtDealNo.Text + "',\n" +
"'" + contactPersonTextBox.Text + "',\n" +
"'" + addressTextBox.Text + "',\n" +
"'" + taxVatNoTextBox.Text + "',\n" +
"'" + commTextBox.Text + "',\n" +
"'" + workTelTextBox.Text + "',\n" +
"'" + cellTextBox.Text + "',\n" +
"'" + faxTextBox.Text + "',\n" +
"'" + emailTextBox.Text + "',\n" +
"'" + notesTextBox.Text + "',\n" +
"'" + DateTime.Now + "')";
SqlCommand cm = new SqlCommand(query1);
string Contact = contactPersonTextBox.Text;
cm.Parameters.AddWithValue("#DealID", txtDealNo.Text);
cm.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
cm.Parameters.AddWithValue("#Address", addressTextBox.Text);
cm.Parameters.AddWithValue("#TaxVatNo", taxVatNoTextBox.Text);
cm.Parameters.AddWithValue("#Comm", commTextBox.Text);
cm.Parameters.AddWithValue("#WorkTel", workTelTextBox.Text);
cm.Parameters.AddWithValue("#Cell", cellTextBox.Text);
cm.Parameters.AddWithValue("#Fax", faxTextBox.Text);
cm.Parameters.AddWithValue("#Email", emailTextBox.Text);
cm.Parameters.AddWithValue("#CreateDate", DateTime.Now);
cm.Parameters.AddWithValue("#Notes", notesTextBox.Text);
cm.CommandText = query1;
cm.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Saved...", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Your usage of parameter is wrong, it should be:
SqlCommand cmdCount =
new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson", cn);
Later you are adding the parameter correctly.
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
To get the count use SqlCommand.ExecuteScalar, instead of using DataReader:
int count = (int) cmdCount.ExecuteScalar();
For the other queries, UPDATE and INSERT, you can use a verbatim string, instead of concatenating strings over multiple lines.
string query = #"UPDATE _1Agent SET DealID = #DealID,
ContactPerson = #ContactPerson,
Address = #Address,
TaxVatNo = #TaxVatNo,
Comm = #Comm,
WorkTel = #WorkTel,
Cell = #Cell,
Fax = #Fax,
Email = #Email,
Web = #Web,
CreateDate = #CreateDate,
Notes = #Notes WHERE id = #id";
Other issues with the code:
You are concatenating strings to form INSERT query, later you are adding parameters, follow the same convention as UPDATE query and then use the parameters.
As pointed out in the other answer, you are not adding parameter#id value for UPDATE command
You are not specifying connection property with your UPDATE and INSERT command:
Specify it like
SqlCommand cm = new SqlCommand(query, cn);
Consider enclosing Connection and Command object in using
statement as it will ensure the proper disposal of unmanaged resources.
I see a few things;
Don't use string concatenation with # sign for parameters. That's wrong usage. Use it like;
"SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson"
and
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
and use ExecuteScalar to get first column of the first row. Using a reader is unnecessary for this command.
Your UPDATE query requires #id value since you declare it in your command as;
cm.Parameters.AddWithValue("#id", yourIDvalue);
Your INSERT query, you never declare your parameters in your command. You just concatenate them with their values. And use verbatim string literal to generate multiline strings instead of using \n.
Please
Read more carefully about parameterized queries and how you can use them.
Give me parameterized SQL, or give me death
You forget to mention parameter name in your select query
SqlCommand cmdCount = new SqlCommand("SELECT count(*) from Agent WHERE ContactPerson = #ContactPerson", cn);
cmdCount.Parameters.AddWithValue("#ContactPerson", contactPersonTextBox.Text);
There are some wrong things .So you can refer #Soner Gönül and #habib answers
And change your insert query.Since you have declared paramertes but you didn't define.So change as follows
string query1 = "INSERT INTO _1Agent (DealID,ContactPerson,Address,TaxVatNo,
Comm, WorkTel, Cell, Fax, Email,Notes,CreateDate)
VALUES ( #DealID , #ContactPerson,#Address ,#TaxVatNo ,
#Comm,#WorkTel , #Cell,#Fax,#Email,#Notes,#CreateDate)";