This question already has answers here:
Inserting Multiple Records into SQL Server database using for loop
(5 answers)
Closed 6 months ago.
can we execute multiple insert statements into MS Access DB 2016 using OLEDB without closing connection/Keeping session alive? I tried moving the OleDB command instantiation, con.open() and con.close() outside of foreach loop but it does not work. Any suggestions?
foreach (var list in lsobj)
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
con.Open();
cmd.CommandText = "INSERT INTO tbl(file_dt, name, created_dt)";
"VALUES (#file_dt,#name,#inserted_dt)";
cmd.Parameters.AddWithValue("#file_dt", list.file_dt.ToString());
cmd.Parameters.AddWithValue("#name", list.name);
cmd.Parameters.AddWithValue("#inserted_dt", list.inserted_dt.ToString());
cmd.ExecuteNonQuery();
con.Close();
}
Yes, you can. As a general rule, before .net days, it was quite much the "norm" to open a connection, and keep it open. However, .net system tends to cache and re-use the connections you made, even when closed.
but, for the most part, yes, you can execute multiple statements, and do them with the same connection.
So, say this code example:
void TestFun()
{
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
using (OleDbCommand cmdSQL = new OleDbCommand("", conn))
{
conn.Open();
// save picture as bytes to DB
byte[] fData = File.ReadAllBytes(txtFile.Text);
string strSQL =
#"INSERT INTO MyPictures (FileName, PictureData)
VALUES(#File, #Data)";
cmdSQL.CommandText = strSQL;
cmdSQL.Parameters.Add("#File", OleDbType.VarWChar).Value = txtFileName.Text;
cmdSQL.Parameters.Add("#Data", OleDbType.Binary).Value = fData;
cmdSQL.ExecuteNonQuery();
// display data in our grid
cmdSQL.CommandText = "SELECT ID, FileName FROM MyPIctures";
cmdSQL.Parameters.Clear();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
dataGridView1.DataSource = rstData;
// do more commands - still same connection
}
}
}
Now, you can't execute multiple SQL statements in one "go" like you can with SQL server (just separate several statements by a ";".
However, you can certain create one connection (and even one command object), and re-use it over and over.
And since the connection and cmdSQL object are inside of a using block, then both objects, and including your connection will be closed and tidy up after you are done.
FYI: USE Parameters . Add, NOT add with value.
Now, in your case? Since it is the same command over and over - but ONLY the parameters change?
Then this (air code warning)
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
con.Open();
cmd.CommandText = #"INSERT INTO tbl (file_dt, name, created_dt)
VALUES (#file_dt,#name,#inserted_dt)";
cmd.Parameters.Add("#file_dt", OleDbType.VarWChar);
cmd.Parameters.Add("#name", OleDbType.VarWChar);
cmd.Parameters.Add("#inserted_dt", OleDbType.VarWChar);
foreach (var list in lsobj)
{
cmd.Parameters["#file_dt"].Value = list.file_dt.ToString();
cmd.Parameters["#name"].Value = list.name;
cmd.Parameters["#inserted_dt"].Value = list.inserted_dt.ToString());
cmd.ExecuteNonQuery();
}
con.Close();
Now, I always wrap above in a using block. But, as above again shows, we are free to create a command object, and use it for "many" commands as per first example. and in the 2nd example, we ONLY have to setup the parameters one time, and then use the same connection, same command object over and over.
This question already has answers here:
How do parameterized queries help against SQL injection?
(6 answers)
Closed 4 years ago.
I'm working on a simple script to query a database based off user input, and I was wondering if there's any chance of injection with something like .net's parameterized queries?
By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.
Here is an example, taken from Here:
private static void UpdateDemographics(Int32 customerID,
string demoXml, string connectionString)
{
// Update the demographics for a store, which is stored
// in an xml column.
string commandText = "UPDATE Sales.Store SET Demographics = #demographics "
+ "WHERE CustomerID = #ID;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
// Use AddWithValue to assign Demographics.
// SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("#demographics", demoXml);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I am trying to add the following details into the Database table. The question. the answer and the topicID[int]
C# Code:
private void AddingQuestions()
{
using (MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=project;username=root;password=***;"))
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO questions (question, answer, topicID) VALUES (#Questions, #Answers, #TopicID);");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Questions", TxtBoxQuestion.Text);
cmd.Parameters.AddWithValue("#Answers", TxtboxAnswer.Text);
cmd.Parameters.AddWithValue("#TopicID", Convert.ToInt32(TxtBoxTopicID.Text));
connection.Open();
cmd.Connection = connection;
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
connection.Close();
}
}
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
at the Line:
cmd.Parameters.AddWithValue("#TopicID", Convert.ToInt32(TxtBoxTopicID.Text));
Furthermore: I know its good practise to use parametrised sql to avoid sql injections. Am I using parametrised sql?
As discussed in the comments, the problem is that you try to convert the Value of a TextBox that actually does not have a value (it is null or empty string) during opening of the Form
Possible solutions:
Do not call the method during startup of the form
Fill the TextBox with a valid default value
To answer the second part of the question:
Yes, you are already using a parameterized query.
This question already has answers here:
SqlCommand INSERT INTO query does not execute
(3 answers)
Closed 7 years ago.
I am using visual studio, i have a connection to an SQL server and im trying to update a table in the database.
I am not recieving any errors nor am i updating anything
Below is the code i have used
protected void Btn1_Click(object sender, EventArgs e)
{
//SQL for insert here.
string MyConnectionString = ConfigurationManager.ConnectionStrings
["testconnect"].ConnectionString;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = MyConnectionString;
myConnection.Open();
SqlCommand cmd = new SqlCommand("insert into Don_Test (ID, Test) values ('" + IDTxt.Text + "','" + TESTTxt.Text + "')", myConnection);
//Call refresh
refreshPage();
myConnection.Close();
}
Actually, you are not executing your query, but just opening connection and closing it later.
Add line of code cmd.ExecuteNonQuery(); before refreshPage().
Also notice - concatenating query text is very bad idea since it leads to SQL injection attack.
Use parameterized query instead.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to insert data from my ASP.NET web application into a SQL Server database table (which I have previously created). The code I have doesn't seem to be working, the error message displays, and the actual data doesn't appear to get saved to the database.
var conn = new SqlConnection("Data Source=SHRIYA\\SQLEXPRESS;Initial Catalog=…;Integrated Security=True");
var insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,#Postal_code,#Phone_Number,#Email,#Password", conn);
insert.Parameters.AddWithValue("#GenerteID",lstuserID.SelectedIndex);
insert.Parameters.AddWithValue("#Name", txtname.Text);
insert.Parameters.AddWithValue("#Surname", txtsurname.Text);
insert.Parameters.AddWithValue("ID_Number", txtid.Text);
insert.Parameters.AddWithValue("#Gender", ddlgender.SelectedItem);
insert.Parameters.AddWithValue("#Address", txtaddress.Text);
insert.Parameters.AddWithValue("#Postal_code", txtpostalcode.Text);
insert.Parameters.AddWithValue("#Phone_Number", txttele.Text);
insert.Parameters.AddWithValue("#Email", txtEmail.Text);
insert.Parameters.AddWithValue("#Password", txtpassword);
try
{
conn.Open();
insert.ExecuteNonQuery();
}
catch (Exception)
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Error When Saving');", true);
}
conn.Close();
One error is to use txtpassword (i.e. a UI control as a whole) as a value for a SqlParameter. Replace it with txtpassword.Text (i.e. the textual value entered into the UI control):
insert.Parameters.AddWithValue("#Password", txtpassword.Text);
Your SQL command text is missing the closing parenthesis ) for VALUES (:
SqlCommand insert = new SqlCommand("Insert Into
tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,
Postal_code,Phone_Number,Email,Password)
values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,
#Postal_code,#Phone_Number,#Email,#Password)", conn);
// ^
insert.Parameters.AddWithValue("ID_Number", txtid.Text);
That should be
insert.Parameters.AddWithValue("#ID_Number", txtid.Text);
SqlCommand insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,#Postal_code,#Phone_Number,#Email,#Password", conn);
SQL syntax is wrong.
Missing ) at the last parameter #Password.
SqlCommand insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,#Postal_code,#Phone_Number,#Email,#Password)", conn);