I want to update a contactInfo database using C#. I need to insert (possibly) multiple people/emergency contacts from a windows form. So I am setting the textboxes on the windows form equal to variables to pass into my query. I know how to do one record per connection, but how would I do two? so for example if a secondary emergency contact was supplied how could I also insert the data provided in txt2fname, txt2lname, txt2phone1, txt2phone2?
SqlConnection con = new SqlConnection("ConnectionStringGoesHere")
{
SqlCommand cmd;
try
{
string emergencyContactInfo = "Insert Into econtactInfo(fname, lname, phone1, phone2) Values(#fname, #lname, #phone1, #phone2)";
cmd = new SqlCommand(emergencyContactInfo, con);
con.Open();
cmd.Parameters.AddWithValue("#fname", txt1fname);
cmd.Parameters.AddWithvalue("#lname", txt1lname);
cmd.Parameters.AddWithValue("#phone1", txt1phone1);
cmd.Parameters.AddWithvalue("#phone2", txt1phone2);
cmd.ExecuteNonQuery();
connection.Close()
}
}
You just need to go something like this..
string emergencyContactInfo = "Insert Into econtactInfo(fname, lname, phone1, phone2) Values(#fname, #lname, #phone1, #phone2)";
cmd = new SqlCommand(emergencyContactInfo, con);
con.Open();
cmd.Parameters.Add("#fname", SqlDbType.<Type>);
<Add the other parameters here>
...
cmd.Parameters["#fname"].Value = txt1fname
<Add parameters values here>
...
cmd.ExecuteNonQuery();
cmd.Parameters["#fname"].Value = txt2fname
<Add parameters values here>
...
cmd.ExecuteNonQuery();
connection.Close()
Try this :
string SqlString =#"Insert into mytable(f1,f2) values ('1','2'),
Insert into mytable(f1,f2) values ('3','4'),
Insert into mytable(f1,f2) values ('5','6'), ";
con.Execute(SqlString);
Or something like this
SqlConnection con = new SqlConnection("ConnectionStringGoesHere")
string emergencyContactInfo = #"Insert Into econtactInfo(fname, lname, phone1, phone2) Values({0}, {1}, {2}, {3})";
con.Open();
for(....)
{
con.Execute(String.Format(emergencyContactInfo ,txt1fname,txt1lname,txt1phone1 txt1phone2));
}
connection.Close();
Related
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-O72COGQ;Initial Catalog=ClinicManagementtest;Integrated Security=True"))
{
con.Open();
SqlCommand sc = new SqlCommand("INSERT INTO Patient_Details VALUES(#Id, #Name, #Age, #Contact No, #Address", con);
sc.Parameters.AddWithValue("#Id", textBox1.Text);
sc.Parameters.AddWithValue("#Name", textBox2.Text);
sc.Parameters.AddWithValue("#Contact No", textBox3.Text);
sc.Parameters.AddWithValue("#Address", textBox5.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
con.Close();
}
You are making a lot of errors here.
First, you have 6 fields in your table and, if you don't give a list
of fields when you make an insert query, then you should add values
for all 6 fields.
Second you have 5 parameters placeholders but you add only 4
parameters and this is another exception.
Last but not least the syntax of the insert statement is formally
wrong because there is no closing parenthesys
So, let's try to fix at the best of our knowledge
string cmdText = #"INSERT INTO Patient_Details
(ID, Name, Age, Gender, [Contact No], Address)
VALUES(#Id,#Name,#Age,#Gender,#ContactNo, #Address)"
using (SqlConnection con = new SqlConnection(....))
{
con.Open();
SqlCommand sc = new SqlCommand(cmdText, con);
sc.Parameters.AddWithValue("#Id", textBox1.Text);
sc.Parameters.AddWithValue("#Name", textBox2.Text);
// For the following two fields, add a value or remove
// the parameters and fix the query text above....
sc.Parameters.AddWithValue("#age", ????);
sc.Parameters.AddWithValue("#gender", ????);
sc.Parameters.AddWithValue("#ContactNo", textBox3.Text);
sc.Parameters.AddWithValue("#Address", textBox5.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
}
Like Sankar Raj pointed out you missed the a ) in the Insert query and a parameter #Age to add.Using space in parameter #Contact No is also not allowed.
You have used using for SqlConnection.I suggest you use the same for SqlCommand also, then you don't need to explicitly Dispose it. And again it seems you are not using try catch that's you were not able to identity the problem.
SUGGESTED CODE
try{
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-O72COGQ;Initial Catalog=ClinicManagementtest;Integrated Security=True"))
{
con.Open();
using (SqlCommand sc = new SqlCommand("INSERT INTO Patient_Details VALUES(#Id, #Name, #Age,#Gender, #ContactNo, #Address)", con)){
sc.Parameters.AddWithValue("#Id", textBox1.Text);
sc.Parameters.AddWithValue("#Name", textBox2.Text);
sc.Parameters.AddWithValue("#Gender", textBox3.Text);
sc.Parameters.AddWithValue("#ContactNo", textBox4.Text);
sc.Parameters.AddWithValue("#Age", textBox5.Text);
sc.Parameters.AddWithValue("#Address", textBox6.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
}
}
}catch(Exception ex){
MessageBox.Show(ex.Message);
}
Note: I've removed con.Close(). Since you are using using statement it will automatically Close & Dispose the Connection and release the resources it uses.
I'm trying to understand how to insert data into my database, so i looked at many tutorials, and i couldn't understand how to do it. one tutorial got me as far as this:
public partial class Register : System.Web.UI.Page{
public string ID, Pass, Email, BDYear, BDMonth, BDDay, FullName;
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack){
ID = Request.Form["ID"];
Pass = Request.Form["PW"];
Email = Request.Form["EMAIL"];
BDYear = Request.Form["BDYear"];
BDMonth = Request.Form["BDMonth"];
BDDay = Request.Form["BDDay"];
FullName = Request.Form["FullName"];
cmd = new SqlCommand("INSERT INTO UserInfo (ID, Pass, Email, BDYear, BDMonth, BDDay, FullName) VALUES (ID, Pass, Email,BDYear, BDMonth, BDDay, FullName)");
}
}
}
But it doesn't actually work, or shows a sign of it working, and i think i need help of someone telling me exactly what to do in my situation.
I don't know if any of what is written here is correct, but please i need guidance.
All the variables are set in the aspx page according to those names.
You should try something like this:
set up your query statement as a string
put your SqlCònnection and SqlCommand into using(..) { ... } blocks to ensure proper disposal
define parameters with explicit types, set their values
open the connection, execute query, close connection
This would be the code to use:
-- your INSERT statement:
string query = "INSERT INTO UserInfo(ID, Pass, Email, BDYear, BDMonth, BDDay, FullName) " +
"VALUES (#ID, #Pass, #Email, #BDYear, #BDMonth, #BDDay, #FullName);";
-- define your connection to the database
using (SqlConnection conn = new SqlConnection("server=.;database=test;Integrated Securiy=SSPI;"))
-- define your SqlCommand
using (SqlCommand cmd = new SqlCommand(query, conn))
{
-- define the parameters and set their values
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ID;
cmd.Parameters.Add("#Pass", SqlDbType.VarChar, 50).Value = Pass;
cmd.Parameters.Add("#Email", SqlDbType.VarChar, 255).Value = Email;
cmd.Parameters.Add("#BDYear", SqlDbType.Int).Value = BDYear;
cmd.Parameters.Add("#BDMonth", SqlDbType.Int).Value = BDMonth;
cmd.Parameters.Add("#BDDay", SqlDbType.Int).Value = BDDay;
cmd.Parameters.Add("#Fullname", SqlDbType.VarChar, 200).Value = Fullname;
-- open connection, execute query, close connection
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
}
Of course, with the parameters, I could only guess what datatypes they would be - you might need to adjust that! Also: the connection string in the constructor of the SqlConnection object of course needs to be adapted to your needs - again, I was just guessing what it might be like - adapt as needed!
You have not connected to the database and also you haven't executed the command.
Here is an example from MSDN:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection%28v=vs.110%29.aspx
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
You should provide connection string which depends on your DB type and location.
You need to define a sqlconnection first else how will the .net framework know which database to use, where its located etc.
sqlconnection con;
sqlcommand cmd;
con = new sqlconection("your connection string goes here");
cmd = new sql command("your query", con); //we are telling cmd that you need to
// fire the query using con which is a connection object which ultimately
// contains database connection information
con.open();
cmd.ExecuteNonQuery();
con.close();
I don't think data adapter is required here for inserting data. Data adapter is generally used when performing "select" queries. Data adapter generally fills the dataset.
More info about creating a connection string can be found on the below links:-
How to create a connection string in asp.net c#
cmd = new SqlCommand("INSERT INTO UserInfo (ID, Pass, Email, BDYear, BDMonth, BDDay, FullName) VALUES ("+ID+", "+Pass+", "+Email+","+BDYear+", "+BDMonth+", "+BDDay+", "+FullName+")");
this may work but i suggest use SqlCommand with parameter.
this articles can help you .
http://msdn.microsoft.com/tr-tr/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06
I get this error in ASP.NET Wizard when I try to use values of TextBox control of previous step.
Error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Contact_Emp".
The conflict occurred in database "KKSTech", table "dbo.Emp", column 'EmpID'.
Is it a problem to access control's values of different steps?
This is the First class that inserts into dbo.Emp table
public void InsertInfo()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String insertstring = #"insert into Emp (EmpID, FirstName, LastName, MiddleName, Mob1, Mob2, Phone, Email1, Email2, EmpDesc)
values (#EmpID, #FirstName, #LastName, #MiddleName, #Mob1, #Mob2)";
SqlCommand cmd = new SqlCommand(insertstring, conn);
cmd.CommandText = insertstring;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.Parameters.AddWithValue("#FirstName", TextBox2.Text);
cmd.Parameters.AddWithValue("#LastName", TextBox3.Text);
cmd.Parameters.AddWithValue("#MiddleName", TextBox4.Text);
cmd.Parameters.AddWithValue("#Mob1", TextBox5.Text);
cmd.Parameters.AddWithValue("#Mob2", TextBox6.Text);
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
And this is the one where I 'm inserting into the table where EmpID is a FK
public void Insertaddress()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String str = #"insert into Contact (Addressline1, Addressline2, CityID, EmpID)
values(#Addressline1, #Addressline2, #CityID, #EmpID)";
SqlCommand cmd = new SqlCommand(str, conn);
cmd.CommandText = str;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#Addressline1", TextBox15.Text);
cmd.Parameters.AddWithValue("#Addressline2", TextBox17.Text);
cmd.Parameters.AddWithValue("#CityID", DropDownList2.SelectedValue);
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
That was my problem.
A foreign key ensures that it cannot have a value in that column that is not also in the primary key column of the referenced table.
In your case , you are inserting EmpID into contact table which is not present in the referenced table of EmpID i.e Emp table.
I have a table student (id, name). Then I have one textbox, for entering the name, when click on submit button, it inserts the data into the database. So how can I insert only to name, not id because id is auto increment?
I tried this
insert into student(id, name) values(,name)
but it is not insert to my table.
This is my code :
protected void Button1_Click(object sender, EventArgs e)
{
string test = txtName.Text;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Person.mdf;Integrated Security=True;User Instance=True");
string sql = "insert into student(name) values ('test')";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
}
INSERT INTO student (name) values ('name')
Omit the id column altogether, it will be populated automatically. To use your variable, you should parameterise your SQL query.
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
You should never attempt to do this by constructing a SQL string containing the input value, as this can expose your code to SQL injection vulnerabilities.
You better use parameters when you insert data.
try
{
string sql = "insert into student(name) values (#name)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#name", test); // assign value to parameter
cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
You don't need to mention the ID in first part.
insert into student(name) values('name')
I was facing this problem and after trying various solution found at stack overflow, i could summarize the experience as follows:
commands executed in command shell of mssql like:
insert into table_name (val1,val2,val3,val4) VALUES ("val1","val2",0,"val4")
go
or
insert into table_name VALUES ("val1","val2",0,"val4")
go
work when typed directly in the mssql database prompt,
But when it is required to use the the insert statement from c#, it is required to be kept in mind that string needs to be surrounded by an additional pair of single quites, around the strings, like in:
SqlConnection cnn;
string connetionString = "Data Source=server_name;Initial Catalog=database_name;User ID=User_ID;Password=Pass_word";
cnn = new SqlConnection(connetionString);
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('val1','val2',0,'val4');", cnn);
//or
//SqlCommand myCommand = new SqlCommand(insert into table_name VALUES ('val1','val2',0,'val4');", cnn);
cnn.Open();
myCommand.ExecuteNonQuery();
cnn.Close();
the problem here is that most people, like myself, try to use <\"> in the place of double quotes <">that is implemented as in the above command line case, and SQL executor fails to understand the meaning of this.
Even in cases where a string needs to be replace, ensure that strings are surrounded by single quotation, where a string concatination looks like a feasible solution, like in:
SqlCommand myCommand = new SqlCommand("insert into table_name (val1,val2,val3,val4) VALUES ('"+val1+"','val2',0,'val4');", cnn);
string sql = "INSERT INTO student (name) values (#name)";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = test;
cmd.ExecuteNonQuery();
Try the following query,
insert into student(name) values(name)
SQL Server internally auto increments the id column when u insert the data since u said it is auto increment. If it is not working, the u have to check the identity column in the db.
use the key word "identity" to auto increment the id column
Refer : http://technet.microsoft.com/en-us/library/aa933196(v=sql.80).aspx
create table table_name( id int PRIMARY KEY IDENTITY )
and you no need to mention the "id" in the insert query
runtime error 'there is already an open datareader associated with this command which must be closed first'
objCommand = new SqlCommand("SELECT field1, field2 FROM sourcetable", objConn);
objDataReader = objCommand.ExecuteReader();
while (objDataReader.Read())
{
objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, '" + objDataReader[0] + "')", objConn);
objInsertCommand.ExecuteNonQuery();//Here is the error
}
objDataReader.Close();
I cannot define any stored procedure here.
Any help would we appreciated.
No need to do all that, just turn on MARS and your problem will get solved. In your connection string just add MultipleActiveResultSets=True;
You can't perform an action on that connection while it's still working on reading the contents of a data reader - the error is pretty descriptive.
Your alternatives are:
1) Retrieve all your data first, either with a DataSet or use the reader to populate some other collection, then run them all at once after the initial select is done.
2) Use a different connection for your insert statements.
How about pulling the data into a DataSet via Fill and then iterate through that to perform your insert via NonQuery?
IDbDataAdapter da;
IDbCommand selectCommand = connection.CreateCommand();
selectCommand.CommandType = CommandType.Text;
selectCommand.CommandText = "SELECT field1, field2 FROM sourcetable";
connection.Open();
DataSet selectResults= new DataSet();
da.Fill(selectResults); // get dataset
selectCommand.Dispose();
IDbCommand insertCommand;
foreach(DataRow row in selectResults.Tables[0].Rows)
{
insertCommand = connection.CreateCommand();
insertCommand.CommandType = CommandType.Text;
insertCommand.CommandText = "INSERT INTO tablename (field1, field2) VALUES (3, '" + row["columnName"].ToString() + "'";
}
insertCommand.Dispose();
connection.Close();
Your best bet would be to read the information you need into a list and then iterating the list to perform your inserts like so:
List<String> values = new List<String>();
using(SqlCommand objCommand = new SqlCommand("SELECT field1, field2 FROM sourcetable", objConn)) {
using(SqlDataReader objDataReader = objCommand.ExecuteReader()) {
while(objDataReader.Read()) {
values.Add(objDataReader[0].ToString());
}
}
}
foreach(String value in values) {
using(SqlCommand objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, '" + value + "')", objConn)) {
objInsertCommand.ExecuteNonQuery();
}
}
INSERT INTO tablename (field1, field2)
SELECT 3, field1 FROM sourcetable
A single SQL statement instead of one per insert. Not sure if this will work for your real-life problem, but for the example you provided, this is a much better query than doing them one at a time.
On a side note, make sure your code uses parameterized queries instead of accepting strings as-is inside the SQL statement - your sample is open to SQL injection.
Several suggestions have been given which work great, along with recommendations for improving the implementation. I hit the MARS limit due to existing code not cleaning up a reader so I wanted to put together a more respectable sample:
const string connectionString = #"server=.\sqlexpress;database=adventureworkslt;integrated security=true";
const bool useMARS = false;
using (var objConn = new System.Data.SqlClient.SqlConnection(connectionString + (useMARS ? ";MultipleActiveResultSets=True" : String.Empty)))
using (var objInsertConn = useMARS ? null : new System.Data.SqlClient.SqlConnection(connectionString))
{
objConn.Open();
if (objInsertConn != null)
{
objInsertConn.Open();
}
using (var testCmd = new System.Data.SqlClient.SqlCommand())
{
testCmd.Connection = objConn;
testCmd.CommandText = #"if not exists(select 1 from information_schema.tables where table_name = 'sourcetable')
begin
create table sourcetable (field1 int, field2 varchar(5))
insert into sourcetable values (1, 'one')
create table tablename (field1 int, field2 varchar(5))
end";
testCmd.ExecuteNonQuery();
}
using (var objCommand = new System.Data.SqlClient.SqlCommand("SELECT field1, field2 FROM sourcetable", objConn))
using (var objDataReader = objCommand.ExecuteReader())
using (var objInsertCommand = new System.Data.SqlClient.SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, #field2)", objInsertConn ?? objConn))
{
objInsertCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("field2", String.Empty));
while (objDataReader.Read())
{
objInsertCommand.Parameters[0].Value = objDataReader[0];
objInsertCommand.ExecuteNonQuery();
}
}
}
Option 1:
Must execute query and load data before running another query.
Option 2:
Add MultipleActiveResultSets=true to the provider part of your connection string. See the example below:
<add name="DbContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=dbName;Persist Security Info=True;User ID=userName;Password=password;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
What version of SQL Server are you using? The problem might be with this:
(from http://msdn.microsoft.com/en-us/library/9kcbe65k.aspx)
When you use versions of SQL Server before SQL Server 2005, while the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader. While in this state, no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the SqlDataReader is called.
So, if this is what's causing your problem, you should first read all the data, then close the SqlDataReader, and only after that execute your inserts.
Something like:
objCommand = new SqlCommand("SELECT field1, field2 FROM sourcetable", objConn);
objDataReader = objCommand.ExecuteReader();
List<object> values = new List<object>();
while (objDataReader.Read())
{
values.Add(objDataReader[0]);
}
objDataReader.Close();
foreach (object value in values)
{
objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, '" + value + "')", objConn);
objInsertCommand.ExecuteNonQuery();
}
Adding this to connection string should fix the problem.
MultipleActiveResultSets=true
Try something like this:
//Add a second connection based on the first one
SqlConnection objConn2= new SqlConnection(objConn.connectionString))
SqlCommand objInsertCommand= new SqlCommand();
objInsertCommand.CommandType = CommandType.Text;
objInsertCommand.Connection = objConn2;
while (objDataReader.Read())
{
objInsertCommand.CommandText = "INSERT INTO tablename (field1, field2) VALUES (3, '" + objDataReader[0] + "')";
objInsertCommand.ExecuteNonQuery();
}
Best Solution:
There is only problem with your "CommandText" value. Let it be SP or normal Sql Query.
Check 1: The parameter value which you are passing in your Sql Query
is not changing and going same again and again in your ExecuteReader.
Check 2: Sql Query string is wrongly formed.
Check 3: Please create simplest code as follows.
string ID = "C8CA7EE2";
string myQuery = "select * from ContactBase where contactid=" + "'" + ID + "'";
string connectionString = ConfigurationManager.ConnectionStrings["CRM_SQL_CONN_UAT"].ToString();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand(myQuery, con);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
con.Close();
In order for it to be disposed easily i use the following coding-template :
`using (SqlConnection connection = new SqlConnection("your connection string"))
{
connection.Open();
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "Select * from SomeTable";
using (SqlDataReader reader = cmd.ExecuteReader())
{
if(reader.HasRows)
{
while(reader.Read()){
// assuming that we've a 1-column(Id) table
int id = int.Parse(reader[0].ToString());
}
}
}
}
connection.Close()
}`