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

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 .

Related

Error in insert query in visual studio

I'm new in this field. Trying to insert the values from textbox to my database table, but I get an error at
adapter.InsertCommand.ExecuteNonQuery();
Can anyone help me solve this?
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql,con);
adapter.InsertCommand = new SqlCommand(sql,con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();
Since your table is called table and that is a SQL reserved word, you have two choices:
Change your table name. This is the only option you should be considering but for completeness;
Quote the name of the table:
insert into [table] values....
You do not list your column name on insert. This means you are also attempting to insert your identity column as well. Always list your column names
insert into NewName (firstname, lastname, username, email, password, contact)
values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')
Yes I've done it .I was using "user" in table column which is not allowed .After changing the column name everything works.
This is the code
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql, con);
adapter.InsertCommand = new SqlCommand(sql, con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();

Why is my SQL code in C# not working?

I wrote a SQL command to save some items in my database. But when I run it, it gives an error message:
And here is my code:
public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
{
if (beoordelingBest < beoordeling)
{
titelBest = titel;
beoordelingBest = beoordeling;
}
string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
command = new SqlCommand(queryString, con);
Can someone please help me with this? I can't figure it out.
Use parametererized queries and do not use string concatination. This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example).
If you have multiple queries each unique parameter value should have its own parameter name/value
Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable
Never reuse connections as global objects, create, use, and destroy them when needed.
Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary.
var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT #a1Voornaam, #a1Achternaam, FilmID from Films WHERE titel = #title";
using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
command.Parameters.Add(new SqlParameter("#a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
command.Parameters.Add(new SqlParameter("#achternaam", SqlDbType.VarChar){Value = achternaam});
command.Parameters.Add(new SqlParameter("#title", SqlDbType.VarChar){Value = title});
con.Open();
command.ExecuteNonQuery();
}
Perhaps one of your values is ');
That would terminate the INSERT statement early, and cause the error.
|
V
INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');
You should use SqlParameters instead of string concatenation.
Are you using TextBoxes? I can't tell for sure. Try something like this, and change to suit your specific needs.
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
try
{
string query = "insert into UserDetail(Name,Address)
values('" + txtName.Text + "','" + txtAddress.Text + "');";
SqlDataAdapter da = new SqlDataAdapter(query, con);
con.Open();
da.SelectCommand.ExecuteNonQuery();
con.Close();
lblmessage.Text = "Data saved successfully.";
}
catch
{
con.Close();
lblmessage.Text = "Error while saving data.";
}
}

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

Int Value in C# does not match with SQL count() value

I'm trying to pass a value from my SQL query count() to c# int Tech_Count but it's displaying different. If I only run the query count, it return 3 but in c#, it's showing -1. Here's my code.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True; AttachDbFilename=C:\Users\anthonyhau\Documents\Lawn Mower\LawnMowerDatabase\LawnMowerDatabase\Database1.mdf");
con.Open();
SqlCommand cmd1 = new SqlCommand("update Tech set Customer_Count = (select IdAndCnt.cnt from (select Tech_Id,count (Tech_id) as cnt from Customers group by Tech_Id ) as IdAndCnt where Tech.Tech_Id = IdAndCnt.Tech_Id)", con);
SqlCommand cmd = new SqlCommand("INSERT INTO Customers (First_Name, Last_Name, Street, City, State, Zip, Phone, Date_Started) VALUES ('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "', '" + textBox6.Text + "', '" + textBox7.Text + "', '" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "')", con);
SqlCommand techcnt = new SqlCommand("Select count(Tech_Id) From Tech", con);
cmd1.ExecuteNonQuery();
cmd.ExecuteNonQuery();
int Tech_Count = techcnt.ExecuteNonQuery();
textBox8.Text = Tech_Count.ToString();
con.Close();
I think you have to use ExecuteScalar instead of executenonquery and it will solve your problem.
int Tech_Count = (int)techcnt.ExecuteScalar();
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
That's because ExecuteNonQuery does not return the count like that for SELECT statements:
From MSDN
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. When a trigger exists on a
table being inserted or updated, the return value includes the number
of rows affected by both the insert or update operation and the number
of rows affected by the trigger or triggers. For all other types of
statements, the return value is -1.
Why are you using ExecuteNonQuery if you are in fact executing a query?? Objects in classes are pretty self explanatory. ExecuteNonQuery is used for update,deletes and inserts so it returns the affected rows. Try this on for size:
SqlCommand techcnt = new SqlCommand("Select #count:=count(Tech_Id) From Tech", con);
techcnt.Parameters.Add("#count", SqlDbType.Int).Direction = ParameterDirection.Output;
techcnt.CommandType = CommandType.Text;
techcnt.ExecuteScalar();
textBox8.Text = techcnt.Parameters["#count"].Value.ToString();
or something shorter like this:
SqlCommand techcnt = new SqlCommand("Select count(Tech_Id) From Tech", con);
textBox8.Text = techcnt.ExecuteScalar().ToString();

Insert statement won't insert Null value

I'm trying to insert a null value into my database from C# like this:
SqlCommand command = new SqlCommand("INSERT INTO Employee
VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text
+ "','" + phone.Text + "','" + DBNull.Value + "')", connection);
DBNull.Value is where a date can be but I would like it to be equal to null but it seems to put in a default date, 1900 something...
Change to:
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text + "','" + phone.Text + "',null)", connection);
DBNull.Value.ToString() returns empty string, but you want null instead.
However this way of building your query can lead to issues. For example if one of your strings contain a quote ' the resulting query will throw error. A better way is to use parameters and set on the SqlCommand object:
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES (#empId,#name,#age,#phone,null)", connection);
command.Parameters.Add(new SqlParameter("#empId", employeeId.Text));
command.Parameters.Add(new SqlParameter("#name", name.Text));
command.Parameters.Add(new SqlParameter("#age", age.Text));
command.Parameters.Add(new SqlParameter("#phone", phone.Text));
Use Parameters.
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES
(#employeeID,#name,#age,#phone,#bdate)",connection);
....
command.Parameters.AddWithValue("#bdate",DBNull.Value);
//or
command.Parameters.Add("#bdate",System.Data.SqlDbType.DateTime).Value=DBNull.Value;
Or try this,
SqlCommand command = new SqlCommand("INSERT INTO Employee
(employeeID,name,age,phone) VALUES
(#employeeID,#name,#age,#phone)",connection);
Change DBNull.Value to the literal null for dynamic SQL:
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text + "','" + phone.Text + "',null)", connection);
Try this:
SqlCommand command = new SqlCommand();
command.ComandText = "insert into employee values(#employeeId, #name, #age, #phone, #someNullVal)";
command.Parameters.AddWithValue("#employeedId", employeedID.Text);
// all your other parameters
command.Parameters.AddWithValue("#someNullVal", DBNull.Value);
This solves two problems. You explicit problem (with inserting a NULL value into the table), and SQL Injection potential.
if you output "'" + DBNull.Value + "'" , you will find that it's '' , which means you insert an empty string instead of null into the DB. So, you just write null:
SqlCommand command = new SqlCommand("INSERT INTO Employee
VALUES ('" + employeeID.Text + "','" + name.Text + "','" + age.Text
+ "','" + phone.Text + "', null)", connection);
try it like this.
SqlCommand command = new SqlCommand("INSERT INTO Employee VALUES ('" + employeeID.Text +
"','" + name.Text + "','" + age.Text + "','" + phone.Text + "','Null')", connection);

Categories