I have a database that contains a Customer table with the following columns : CustID, CustName, ICNumber, ContactNumber and Address. It is a service-based database.
string localdb = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(localdb);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Customer(CustID,CustName,ICNumber,ContactNumber,Address)values(#CustID,#CustName,#ICNumber,#ContactNumber,#Address)", con);
cmd.Parameters.AddWithValue("#CustID", txtCustID.Text);
cmd.Parameters.AddWithValue("#CustName", txtCustName.Text);
cmd.Parameters.AddWithValue("#ICNumber", txtICNum.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.ExecuteNonQuery();
con.Close();
The code compiles and runs. The problem I am having is that the record is not added into the table after cmd.ExecuteNonQuery(); is called.
Why is the record not showing up in the database table?
You forgot to close the quotes " on the insert command. It is nice to use try/catch to avoid problems with your insert, for sample:
string localdb = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
try
{
SqlConnection con = new SqlConnection(localdb))
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Customer(CustID, CustName, ICNumber, ContactNumber, Address) VALUES (#CustID, #CustName, #ICNumber, #ContactNumber, #Address)", con);
cmd.Parameters.AddWithValue("#CustID", txtCustID.Text);
cmd.Parameters.AddWithValue("#CustName", txtCustName.Text);
cmd.Parameters.AddWithValue("#ICNumber", txtICNum.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.ExecuteNonQuery();
}
catch
{
// some errors
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
Related
I'm trying to save data from textboxes to a database, the new data appears in the grid, but it doesn't appear in the database table. When I close the application and restart it, the data which appeared in the grid disappears. There is no error, but no data is uploaded. It works if I hardcode the path but I wanted to use the DataDirectory so that it can be used on other computers. The database is set to Copy if newer (for the copy to output directory). Could someone help?
if (dialogResult == DialogResult.Yes)
{
SqlCommand cmd;
SqlConnection con;
con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = |DataDirectory|\TestDatabase.mdf;Integrated Security=True");
con.Open();
cmd = new SqlCommand("INSERT INTO Patient (FirstName, LastName, DOB) VALUES (#FirstName,#LastName,#DOB)", con);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#DOB", dateTimePicker1.Text);
cmd.ExecuteNonQuery();
con.Close();
SqlDataAdapter SqlDA = new SqlDataAdapter("SELECT * FROM Patient", con);
DataTable dtbl = new DataTable();
SqlDA.Fill(dtbl);
dataGridView1.DataSource = dtbl;
}
I am unable to send lasted inserted autoincrement id value to another table
this is my code
i am getting error is Must declare the scalar variable "#userid".
int ID;
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()", cn);
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
cmd.ExecuteNonQuery();
ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
SqlCommand cmd2 = new SqlCommand("insert into sampfk values(#emailid,#address,#userid)", cn);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text);
cmd2.Parameters.AddWithValue("#userid", ID);
cn.Open();
cmd2.ExecuteNonQuery();
cn.Close();
cmd.Dispose();
TextBox3.Text = "";
TextBox4.Text = "";
I think I got your problem.you have written
SqlCommand cmd2 = new SqlCommand("insert into sampfk values (#userid, #address, #emailid)", cn);
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text)
but executing
cmd2.ExecuteNonQuery();
you should add parameter in cmd2 not cmd like as
cmd2.Parameters.AddWithValue("#userid", ID);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text)
You can do above in single step, you should use using more and try to nest query if possible. Opening TCP connection frequently has some acknowledgement overheads.
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString))
{
string query = #"INSERT INTO sampdb VALUES (#name,#phone);
INSERT INTO sampfk VALUES (SCOPE_IDENITTY(), #address, #emailid); ";
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cmd.ExecuteNonQuery();
}
}
Check the following line.
ID = Convert.ToInt32(cmd.ExecuteScalar());
If this doesn't return anything, then use a default value for ID, maybe 0.
Or add a default value in the declaration as int id = 0;
try this
using (SqlConnection cn = new SqlConnection(connectionStr))
{
string sql1 = "insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()";
using (SqlCommand cmd = new SqlCommand(sql1, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
ID = cmd.ExecuteNonQuery();
}
//ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
string sql2 = "insert into sampfk values (#userid, #address, #emailid)";
using (SqlCommand cmd = new SqlCommand(sql2, cn))
{
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cn.Open();
cmd.ExecuteNonQuery();
}
con.Dispose();
con.Close();
}
I have binded 3 comboboxes separately to 3 different tables. Whenever i select value for metroComboBox2, it gives me this error "Column 'Cor_ID' is constrained to be unique. Value '103' is already present." I don't why this error is coming. What is the cause for this error?
con = new SqlConnection(constr);
con.Open();
DataTable dt = new DataTable();
String query = "Insert into Teacher (ID,Name,FName,Age,Qualification,Dep_ID,Cor_ID,Sem_ID,Password) VALUES(#ID,#Name,#FName,#Age,#Qualification,#Dep_ID,#Cor_ID,#Sem_ID,#Password)";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID", metroTextBox1.Text);
cmd.Parameters.AddWithValue("#Name", metroTextBox2.Text);
cmd.Parameters.AddWithValue("#FName", metroTextBox3.Text);
cmd.Parameters.AddWithValue("#Age", metroTextBox4.Text);
cmd.Parameters.AddWithValue("#Qualification", metroTextBox5.Text);
cmd.Parameters.AddWithValue("#Dep_ID", metroComboBox1.GetItemText(metroComboBox1.SelectedItem));
cmd.Parameters.AddWithValue("#Cor_ID", metroComboBox2.GetItemText(metroComboBox2.SelectedItem));
cmd.Parameters.AddWithValue("#Sem_ID", metroComboBox3.GetItemText(metroComboBox3.SelectedItem));
cmd.Parameters.AddWithValue("#Password", metroTextBox7.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted");
}
I'm trying to insert new values into my database using visual studio and here is my code:
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = dbconnectionstring;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Data_ConfigInfo (TypeID, Name, ValidFromDate, ValidToDate, ValidFromSOP, ValidToSOP, Description)" +
"VALUES(#TypeID, #Name, #ValidFromDateTime, #ValidToDateTime, #ValidFromSOP, #ValidToSOP, #Description)";
cmd.Parameters.AddWithValue("TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("Name", Logg.Name);
if(Logg.ValidFrom.Equals(null)) {
cmd.Parameters.AddWithValue("#ValidFromDateTime", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#ValidFromDateTime", Logg.ValidFrom);
}
if (Logg.ValidTo.Equals(null))
{
cmd.Parameters.AddWithValue("#ValidToDateTime", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#ValidToDateTime", Logg.ValidFrom);
}
cmd.Parameters.AddWithValue("#ValidFromSOP", Logg.ValidFromSOP);
cmd.Parameters.AddWithValue("#ValidToSOP", Logg.ValidToSOP);
cmd.Parameters.AddWithValue("#Description", Logg.Description);
cmd.ExecuteNonQuery();
conn.close();
conn.dispose();
But at the line
cmd.ExecuteNonQuery();
I get the error
invalid column name for ValidToDateTime and ValidFromDateTime.
Both are datetime variables. I can't seem to find the error. Any ideas?
This is how my datatable looks
Your DB table has columns ValidFromDateTime, ValidToDateTime, but your column list in the INSERT statement has ValidFromDate, ValidToDate. Are you sure that it is not a typo when posting here?
Did you forgot '#'?
cmd.Parameters.AddWithValue("TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("Name", Logg.Name);
cmd.Parameters.AddWithValue("#TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("#Name", Logg.Name);
i am getting this error so often, i can't find out what's wrong in here?
con.Open();
String query = "INSERT INTO user (username,[password]) values(a,b)";
OleDbCommand cmd1 = new OleDbCommand(query, con);
cmd1.Parameters.AddWithValue("a",textBox1.Text);
cmd1.Parameters.AddWithValue("b", textBox2.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("User Account Created");
this.Close();
SqlParameters should start with # like #Name. try this:
con.Open();
String query = "INSERT INTO user (Username, [Password]) values(#Username, #Password)";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#Username",textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("User Account Created");
this.Close();
Read Using Variables and Parameters