Mysql give example how insert rows with prepare statement and .NET:
http://dev.mysql.com/doc/refman/5.5/en/connector-net-programming-prepared.html
Its looks that its works like that,because in the end of each iteration call to:cmd.ExecuteNonQuery():
INSERT INTO VALUES()...;INSERT INTO VALUES()...;INSERT INTO VALUES()...;
Can it done with use of prepare statement like that:
INSERT INTO all values...
More explanations::
The code in mysql example (cmd.ExecuteNonQuery() in each iteration):
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
conn.ConnectionString = strConnection;
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO myTable VALUES(NULL, #number, #text)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#number", 1);
cmd.Parameters.AddWithValue("#text", "One");
for (int i=1; i <= 1000; i++)
{
cmd.Parameters["#number"].Value = i;
cmd.Parameters["#text"].Value = "A string value";
cmd.ExecuteNonQuery();
}
}
*The code that i want to have like that(cmd.ExecuteNonQuery(); after all iterations): *
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
conn.ConnectionString = strConnection;
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO myTable VALUES(NULL, #number, #text)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#number", 1);
cmd.Parameters.AddWithValue("#text", "One");
for (int i=1; i <= 1000; i++)
{
cmd.Parameters["#number"].Value = i;
cmd.Parameters["#text"].Value = "A string value";
}
cmd.ExecuteNonQuery();
}
Try this:
using (var connection = new MySqlConnection("your connection string"))
{
connection.Open();
// first we'll build our query string. Something like this :
// INSERT INTO myTable VALUES (NULL, #number0, #text0), (NULL, #number1, #text1)...;
StringBuilder queryBuilder = new StringBuilder("INSERT INTO myTable VALUES ");
for (int i = 0; i < 10; i++)
{
queryBuilder.AppendFormat("(NULL,#number{0},#text{0}),", i);
//once we're done looping we remove the last ',' and replace it with a ';'
if (i == 9)
{
queryBuilder.Replace(',', ';', queryBuilder.Length - 1, 1);
}
}
MySqlCommand command = new MySqlCommand(queryBuilder.ToString(), connection);
//assign each parameter its value
for (int i = 0; i < 10; i++)
{
command.Parameters.AddWithValue("#number" + i, i);
command.Parameters.AddWithValue("#text" + i, "textValue");
}
command.ExecuteNonQuery();
}
Related
I have 1000 hiddenfield. How can i put their value in sql database using for loop. Like:
for (int i = 1; i < 1000; i++)
{
Control hiddenfield = this.FindControl("HiddenField" + i);
String p = Convert.ToString(hiddenfield.Value);
string sqlquery = ("INSERT INTO [" + table_name2 + "] (CT1) VALUES ('" + p + "')");
SqlCommand command = new SqlCommand(sqlquery, Connection);
command.ExecuteNonQuery();
}
change tablename as requred!
string query = "INSERT INTO tablename ( CT1 ) VALUES ( #value )";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(query, con);
try
{
cmd.Parameters.Add("#value", System.Data.SqlDbType.VarChar);
con.Open();
for (int i = 1; i < 1000; i++)
{
Control hiddenfield = this.FindControl("HiddenField" + i);
String p = Convert.ToString(hiddenfield.Value);
cmd.Parameters["#value"].Value = p;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//Show exception as required!
}
finally
{
con.Close();
con.Dispose();
cmd.Dispose();
}
Everything works fine except the labels[i]. The loop is always writing in htmlLabel1 and never in htmlLabel2 etc.
Why does the iteration doesn't work by labels[i] but at Reader.GetValue(i) just fine?
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT number FROM numbers ORDER BY RAND() LIMIT 2; ";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
HtmlLabel[] labels = new HtmlLabel[] {
htmlLabel1,
htmlLabel2,
htmlLabel3
};
for (int i = 0; i < Reader.FieldCount; i++)
{
labels[i].Text = Reader.GetValue(i).ToString();
Console.WriteLine(Reader.GetValue(i).ToString());
}
}
connection.Close();
There is only one field so Reader.FieldCount will return 1 every time.
if you want to loop through rows use the following code
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT number FROM numbers ORDER BY RAND() LIMIT 2; ";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
int i=0;
HtmlLabel[] labels = new HtmlLabel[] {
htmlLabel1,
htmlLabel2,
htmlLabel3
};
while (Reader.Read())
{
//for (int i = 0; i < Reader.FieldCount; i++)
//{
labels[i].Text = Reader[0].ToString();
Console.WriteLine(Reader[0].ToString());
//}
i +=1;
}
connection.Close();
My database tables includes columns like that id,name,surname,phone,address,date. Id is automatically increasing.
name=joe|surname=clark|phone=23132131|address=jdsakldjakldja|date=11.02.2015 14:30:45
name=betty|surname=ugly|phone=32112121|address=dsadaewqeqrsa|date=11.02.2015 14:30:45
This is my INSERT codes
string connStr = #"Data Source=ANLZ\SQLEXPRESS;Initial Catalog=testdb; Trusted_Connection=True;";
string createQuery = "INSERT INTO tbl_test(name,surname,phone,address,date) VALUES(#name,#surname,#phone,#address,#date)";
SqlConnection conn;
SqlCommand cmd;
string[] importfiles = Directory.GetFiles(#"C:\Users\An\Desktop\", "test.txt");
using (conn)
{
using (cmd = new SqlCommand(createQuery, conn))
{
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#surname", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#phone", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#address", SqlDbType.NVarChar, 200);
cmd.Parameters.Add("#date", SqlDbType.DateTime);
foreach (string importfile in importfiles)
{
string[] allLines = File.ReadAllLines(importfile);
baglanti.Open();
for (int index = 0; index < allLines.Length; index++)
{
string[] items = allLines[index].Split(new[] { '|' })
.Select(i => i
.Split(new[] { '=' })[1])
cmd.Parameters["#name"].Value = items[0];
cmd.Parameters["#surname"].Value = items[1];
cmd.Parameters["#phone"].Value = items[2];
cmd.Parameters["#address"].Value = items[3];
cmd.Parameters["#date"].Value = items[4];
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
I would like to update and delete certain text to my database. Also i don't need to save same records with same id. How can i do it?
The ID of any Table should have AUTO_INCREMENT and be of BIGINT or INT type, and code never set the ID, the SQL Server does that.
To update you would make a new SQLCommand of and update type.
string connStr = #"Data Source=ANLZ\SQLEXPRESS;Initial Catalog=testdb; Trusted_Connection=True;";
int updateId = int.Parse(formTextBox.Text); //Or where ever you set the ID to when it is pulled from the database.
string updateCommand = "UPDATE tbl_test SET [surname]=#surname WHERE ID = #id";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = conn;
comm.CommandText = updateCommand;
comm.CommandType = CommandType.Text
comm.Parameters.AddWithValue("#surname", items[1])
comm.Parameters.AddWithValue("#id",updateId);
try
{
comm.Open();
conn.ExecuteNonQuery();
}
catch(OleDbException ex)
{
//Do some error catching Messagebox/Email/Database entry 'Or Nothing'
}
}
}
Deleting is Much easier
string connStr = #"Data Source=ANLZ\SQLEXPRESS;Initial Catalog=testdb; Trusted_Connection=True;";
int updateId = int.Parse(formTextBox.Text); //Or where ever you set the ID to when it is pulled from the database.
string deleteComand = "Delete FROM tbl_test WHERE ID = #id";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = conn;
comm.Parameters.AddWithValue("#id", updateId);
try
{
comm.Open();
conn.ExecuteNonQuery();
}
catch (OleDbException ex)
{
//Do some error catching Messagebox/Email/Database entry 'Or Nothing'
}
}
}
Couple things to Note - Using statements, and Try Catch Blocks.
Using will Dispose of and Connection or other object that has a Dispose implemented.
Try Catch will grab any errors that come from doing the Database call, unable to connect, or the Row to Update could not be updated.
How i can change that Update codes?
public string updateQuery = "UPDATE tbl_test SET name=#name,surname=#surname,phone=#phone,address=#address,date=#date WHERE id=#id ";
// ...
conn = new SqlConnection(connStr);
try
{
string[] importfiles = Directory.GetFiles(#"C:\Users\An\Desktop\", "test.txt");
using (conn)
{
using (cmd = new SqlCommand(updateQuery, conn))
{
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#surname", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#phone", SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#address", SqlDbType.NVarChar, 200);
cmd.Parameters.Add("#date", SqlDbType.DateTime);
cmd.Parameters.Add("#id", SqlDbType.Int);
foreach (string importfile in importfiles)
{
string[] allLines = File.ReadAllLines(importfile);
conn.Open();
for (int index = 0; index < allLines.Length; index++)
{
string[] items = allLines[index].Split(new[] { '|' })
.Select(i => i
.Split(new[] { '=' })[1])
.ToArray();
cmd.Parameters["#name"].Value = items[0];
cmd.Parameters["#surname"].Value = items[1];
cmd.Parameters["#phone"].Value = items[2];
cmd.Parameters["#address"].Value = items[3];
cmd.Parameters["#date"].Value = items[4];
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
}
This is for delete
public string deleteQuery = "DELETE FROM tbl_test WHERE id=#id";
// ...
conn = new SqlConnection(connStr);
try
{
string[] importfiles = Directory.GetFiles(#"C:\Users\An\Desktop\", "test.txt");
using (conn)
{
using (cmd = new SqlCommand(deleteQuery, baglanti))
{
cmd.Parameters.Add("#id", SqlDbType.Int);
foreach (string importfile in importfiles)
{
string[] allLines = File.ReadAllLines(importfile);
conn.Open();
for (int index = 0; index < allLines.Length; index++)
{
string[] items = allLines[index].Split(new[] { '|' })
.Select(i => i
.Split(new[] { '=' })[1])
.ToArray();
cmd.Parameters["#name"].Value = items[0];
cmd.Parameters["#surname"].Value = items[1];
cmd.Parameters["#phone"].Value = items[2];
cmd.Parameters["#address"].Value = items[3];
cmd.Parameters["#date"].Value = items[4];
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
}
For Select it is a little more involved.
**public string selectQuery= "Select * FROM tbl_test" ;
conn = new SqlConnection(connStr);
try
{
using (conn)
{
using (cmd = new SqlCommand(selectQuery, conn))
{
using(var dataReader = cmd.ExecuteReader())
{
while(datareader.reader())
{
//Read the datareader for values and set them .
var id = datareader.GetInt32(0);
}
}
}
}
}**
I want to delete every item in the array from the database.
string[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
for (int i = 0; i <= ids.Length; i++) {
string val = ids[i];
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Parameters.AddWithValue("#p1", val);
}
When I run this the line
string val = ids[i];
gives me an error which says:
Index was outside the bounds of the array.
What's wrong with this?
This is my whole code UPDATED
string connString = "Server=192.168.1.100;Database=product;Uid=newuser;Pwd=password";
MySqlConnection conn = new MySqlConnection(connString);
string[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
try
{
MySqlCommand cmd1 = new MySqlCommand();
conn.Open();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Parameters.AddWithValue("#p1", "");
for (int i = 0; i < ids.Length; i++)
{
string val = ids[i];
cmd1.Parameters[0].Value = val;
cmd1.ExecuteNonQuery();
}
MessageBox.Show("Checkout Successful");
}
Arrays in .NET are zero based and thus the valid indexes go from zero to length - 1.
You should change your code to
for (int i = 0; i < ids.Length; i++)
As pointed by other answer you loop also fails to call cmd1.ExecuteNonQuery and it seems that you don't have associated a connection to the MySqlCommand (thus it will not work at all).
An interesting variation on your code could be to create a single string with all of your commands and submit the command just one time.
Beware that this is not recommended unless you are absolutely sure that your ID are just numbers and not coming from user input
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= ids.Length; i++)
sb.AppendFormat("Delete from tblindividualproduct where ProductID = {0};", ids[i]);
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = sb.ToString();
cmd1.Connection = connection;
cmd1.ExecuteNonQuery();
Array indexes go from 0 up to Length - 1, so you need to stop the loop before i == ids.Length. Try replacing the <= with <. Also, don't forget to call ExecuteNonQuery to execute your command.
for (int i = 0; i < ids.Length; i++) {
string val = ids[i];
MySqlCommand cmd1 = new MySqlCommand(conn);
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#p1", val);
cmd1.ExecuteNonQuery();
}
You can also set up the command outside of the loop and only set the parameter and execute the command inside the loop:
MySqlCommand cmd1 = new MySqlCommand(conn);
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#p1", "");
for (int i = 0; i < ids.Length; i++) {
string val = ids[i];
cmd1.Parameters[0].Value = val;
cmd1.ExecuteNonQuery();
}
This will be much more efficient as there's only one call to the DB, plus there's no need anymore to iterate through yours ids collection.
string[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID IN (" + String.Join(",", ids) + ")";
Your index goes from 0 to your length -1 like this:
tring[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
for (int i = 0; i < ids.Length; i++) {
string val = ids[i];
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Parameters.AddWithValue("#p1", val);
}
And Index was outside the bounds of the array. means that your accessed an element that does not exist with that index.
How to use parameters in IN Clause sql informix
StringBuilder cmdTxt = new StringBuilder();
cmdTxt.Append(" SELECT COUNT(emp_num) ");
cmdTxt.Append(" FROM tbl1 WHERE year IS NULL AND calc_year = ? AND camp IN (,,,)");
using (var myIfxCmd = new IfxCommand(cmdTxt.ToString(), con))
{
myIfxCmd.CommandType = CommandType.Text;
myIfxCmd.Parameters.Add("calc_year", IfxType.Integer);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
myIfxCmd.Parameters[0].Value = calcYear;
res = int.Parse(myIfxCmd.ExecuteScalar().ToString());
}
I don't know how to handle passing parameters to camp IN (,,,,)//Set of numbers
I've something like this
IDbCommand cmd = connection.CreateCommand(); //connection has been instantiated
cmd.CommandTimeout = connection.ConnectionTimeout;
var query = #"SELECT COUNT(emp_num)
FROM tbl1 WHERE year IS NULL AND calc_year = #year AND camp IN ({0})";
cmd.Parameters.Add(new SqlParameter("#year", calcYear));
var sb = new StringBuilder();
//ids is a list/array of ids i want in the in clause
for (int i = 0; i < ids.Count; i++)
{
sb.AppendFormat("#p{0},", i);
cmd.Parameters.Add(new SqlParameter("#p" + i, ids[i]));
}
if (sb.Length > 0) { sb.Length -= 1; }
string cmdText = string.Format(query, sb.ToString());
cmd.CommandText = cmdText;
cmd.Connection = connection;
var reader = cmd.ExecuteReader();