I already asked a question "Timeout expired, optimize query" with problem for a time to respond sql server for my query :
using (SqlConnection sqlConn = new SqlConnection(SqlServerMasterConnection))
{
if (sqlConn.State != ConnectionState.Open) sqlConn.Open();
using (SqlCommand cmd = new SqlCommand("select DT.* from DetailTable DT, BillTable BT, PackageTable PT
where PT.Id= BT.IdPackage and DT.IdBill= BT.Id
and PT.CodeCompany = #codeCompany and PT.Date between #begin and #end",
sqlConn))
{
cmd.Parameters.Add(new SqlParameter(#begin , beginDate));
cmd.Parameters.Add(new SqlParameter("#end", endDate));
cmd.Parameters.Add(new SqlParameter("#codeCompany", codeCompany));
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//work todo
}
}
}
}
it take 28 sec for 20,000 record,
the strange behavior that I wrote this
using (SqlConnection sqlConn = new SqlConnection(SqlServerMasterConnection))
{
if (sqlConn.State != ConnectionState.Open) sqlConn.Open();
using (SqlCommand cmd = new SqlCommand("select DT.* from DetailTable DT, BillTable BT, PackageTable PT where PT.Id= BT.IdPackage and DT.IdBill= BT.Id
and PT.CodeCompany = #codeCompany and PT.Date between '" + beginDate + "' and '" + endDate + "'"
,sqlConn))
{
cmd.Parameters.Add(new SqlParameter("#codeCompany", codeCompany));
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//work todo
}
}
}
}
I changed #date with the sent value without SqlParameter and I got the result in 0 sec !!
any suggestion for this result
PS :
we save the date in the DataBase as string YYYYMMDD (PT.Date is a varchar(8))
beginDate and enddate are string like (20130904)
If your query isn't changing in structure and you're executing it with the same parameters then perhaps SQL Server is caching the results of your query, see this question for a similar issue.
Related
Am working on small project and am new to coding, i want the system to be a booking system whenever specific bus is booked for specific date then that bus will be specific to that date. for example Bus12 is booked to be used on 21 of Aug then if by mistake the admin tries to book the same bus for something else prevent that booking based on checking the date and busno. am simply using web forms, below is my database table and behind code.please help me am not getting any error nothing is stored in my database table when i refresh it.i want if the entered date and Busno is same as the one in table then prevent booking.
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["MyDatabase1ConnectionString"].ConnectionString;
tbDate.Text = Calendar1.SelectedDate.ToShortDateString();
using (SqlConnection con = new SqlConnection(cs))
{
string check = "SELECT BusNo, Date FROM Ticket WHERE (BusNo = #busno) AND(Date = #NewDate))";
SqlCommand cmd = new SqlCommand(check, con);
cmd.Parameters.AddWithValue("#busno", tbBusno.Text);
cmd.Parameters.AddWithValue("#NewDate", DateTime.Parse(tbDate.Text));
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (rdr.HasRows)
{
Response.Write("double booking");
}
else
{
string insertQuery = "INSERT INTO Ticket (BusNo, Date, Time,Bickup,DropOff,Fare) VALUES (#busno ,#date , #time , #bickup , #dropoff ,#fare )";
SqlCommand cmd2 = new SqlCommand(insertQuery, con);
cmd2.Parameters.AddWithValue("#busno", tbBusno.Text);
cmd2.Parameters.AddWithValue("#date", DateTime.Parse(tbDate.Text));
cmd2.Parameters.AddWithValue("#time", tbTime.Text);
cmd2.Parameters.AddWithValue("#dropoff", tbDrop.Text);
cmd2.Parameters.AddWithValue("#bickup", tbBickup.Text);
cmd2.Parameters.AddWithValue("#fare", int.Parse(tbfare.Text));
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
}
}
}
}
Can try removing the while (rdr.Read()) portion ?
So your code will be
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
Response.Write("double booking");
}
else
{
string insertQuery = "INSERT INTO Ticket (BusNo, Date, Time,Bickup,DropOff,Fare) VALUES (#busno ,#date , #time , #bickup , #dropoff ,#fare )";
SqlCommand cmd2 = new SqlCommand(insertQuery, con);
cmd2.Parameters.AddWithValue("#busno", tbBusno.Text);
cmd2.Parameters.AddWithValue("#date", DateTime.Parse(tbDate.Text));
cmd2.Parameters.AddWithValue("#time", tbTime.Text);
cmd2.Parameters.AddWithValue("#dropoff", tbDrop.Text);
cmd2.Parameters.AddWithValue("#bickup", tbBickup.Text);
cmd2.Parameters.AddWithValue("#fare", int.Parse(tbfare.Text));
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
}
I am trying to select then insert a datetime from Table 1 to Table 2. I have successfully insert the data. However, the datetime shown in Table 2 is 0000-00-00 00:00:00. Idk where is the error. Someone please help me with this problem. I am struggling with this. And is this the correct way to SELECT then insert ? (Select from Table 1 then INSERT into Table 2)
try
{
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
Please try with this
try
{
string myConnectionString;
myConnectionString = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new
MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
DateTime assignDate = DateTime.Now;
DateTime.TryParseExact(assign, out assignDate);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth
(userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name,
#stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assignDate);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
}
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
cmd.Parameters.AddWithValue("#stupid4", GetDateString(assign));
Have a method like this:
public static string GetDateString(string date)
{
DateTime theDate;
if (DateTime.TryParseExact(date, "dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate))
{
// the string was successfully parsed into theDate
return theDate.ToString("dd/MM/yyyy HH:mm:ss");
}
else
{
// the parsing failed, return some sensible default value
return string.Empty;
}
}
You need to use .ExecuteReader() the use .Read() to move to each row in the result set. If you are sure the exactly one row will be returned, use .ExecuteScalar() instead. Research on the difference of both online. Below is an example using .ExecuteReader().
I also re-wrote to use using statements to simplify a bit but not deviate too much from your original code so you do not need to worry about closing and disposing resources since they inherit from IDisposable and will do that automatically once they exit the using block:
string assign = DateTime.Now.ToString();
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
string select = "Select time from assign where userId=#name";
using (MySqlConnection con = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand(select))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", txtValue.Text);
using (MySqlDataReader cursor = cmd.ExecuteReader())
{
while (cursor.Read())
{
assign = cursor["time"];
}
}
}
string insert = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
using (MySqlCommand cmd = new MySqlCommand(insert))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.ExecuteNonQuery();
}
}
I am trying to execute a INSERT statement on a mySQL DB in C#:
I read my other articles but could not find the right solution!!!!
This fails with the error: Fatal error encountered during command execution.
Any ideas on why this would fail?
string sqlQuery;
string sqlQuery2;
int countCat;
sqlQuery = "INSERT INTO xs_butiks (siteName,butikCode,butikCategory,butikTitle,butikLink,butikImgLink,butikHtmlCode,butikEndTime,butikStatus) VALUES (#SITE,#CODE,#CATEGORY,#TITLE,#LINK,#IMGLINK,#HTMLCODE,#ENDTIME,#STATUS)";
foreach (DataRow row in butiksTableTrendyol.Rows)
{
sqlQuery2 = "SELECT * FROM xs_butiks WHERE siteName='Trendyol' AND butikCode='" + row["butikCode"] + "'";
lock (dblock)
{
if (con.State != ConnectionState.Open) con.Open();
using (MySqlCommand cmd2 = new MySqlCommand(sqlQuery2, con))
{
countCat = Convert.ToInt32(cmd2.ExecuteScalar());
if (countCat <= 0)
{
lock (dblock)
{
//open connection
if (con.State != ConnectionState.Open) con.Open();
using (MySqlCommand cmd = new MySqlCommand(sqlQuery, con))
{
cmd.CommandText = sqlQuery;
cmd.Parameters.AddWithValue("#SITE", "Trendyol");
cmd.Parameters.AddWithValue("#CODE", row["butikCode"]);
cmd.Parameters.AddWithValue("#CATEGORY", row["butikCategory"]);
cmd.Parameters.AddWithValue("#TITLE", row["butikTitle"]);
cmd.Parameters.AddWithValue("#LINK", row["butikLink"]);
cmd.Parameters.AddWithValue("#IMGLINK", row["butikImgLink"]);
cmd.Parameters.AddWithValue("#HTMLCODE", string.Empty);
DateTime date = DateTime.Parse(row["butikEndTime"].ToString());
cmd.Parameters.AddWithValue("#ENDTIME", date);
cmd.Parameters.AddWithValue("#STATUS", "pending");
cmd.ExecuteNonQuery();
var ID = cmd.LastInsertedId;//get inserted ID
row["butikID"] = ID;//update dataTable
}
//close connection
if (con.State != ConnectionState.Closed) con.Close();
}
}
}
if (con.State != ConnectionState.Closed) con.Close();
}
/********************************************************************/
while (isLockedTrendyolButik) ;
Task.Factory.StartNew(() =>
{
GetTrendyolProducts(row, doc);
}
);
Interlocked.Increment(ref butikCounterTrendyol);//afzayesh yek vahedie globalCounter bad az har request movazi
if (butikCounterTrendyol == 10) isLockedTrendyolButik = true; //age globalCounter be 10 resid dg request ersal nemishe ta in 10ta tamom beshe. adade 10 ro mitonid be meghdare delkhah bar asase ghodrate server taghir dad. ta zamani ke timeOut ijad nashe in adad ghabele afzayeshe.
}
It's very possible its a bad datetime.
try this:
DateTime date;
bool goodDate = DateTime.TryParse(row["butikEndTime"].ToString(), out date);
if (goodDate)
cmd.Parameters.AddWithValue("#ENDTIME", date);
else
cmd.Parameters.AddWithValue("#ENDTIME", DateTime.MinValue);
I'am making a time attendance system and I don't know how to store datetime in database. I really need some help with my system if anyone has any code for time attendance please share your Code a little help would do thanks..
Here is my Code:
con = newSqlConnection(#"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
dt = new DataTable();
cmd = new SqlCommand(#"SELECT EmpID FROM data WHERE EmpID='" + Code.Text + "'", con);
con.Open();
sdr = cmd.ExecuteReader();
int count = 0;
while (sdr.Read())
{
count = count + 1;
}
con.Close();
if (count == 1)
{
con.Open();
DateTime dtn = DateTime.Now;
dtn = Convert.ToDateTime(DateTime.Now.ToString("hh:mm"));
string query = #"INSERT INTO Time (TimeIn) Values ('" + dtn + "')";
cmdd = new SqlCommand(query, con);
sdr = cmdd.ExecuteReader();
sdr.Read();
dataGridView.DataSource = databaseDataSet.Time ;
con.Close();
MessageBox.Show("Verify Ok");
}
else
{
MessageBox.Show("Please Try Again");
}
Do not use ExecuteReader() but ExecuteNonQuery(); add query parameters, do not modify query text, technically it could be something like that:
...
if (count == 1) {
...
DateTime dtn = DateTime.Now;
string query =
#"insert into Time (
TimeIn)
values (
#TimeIn)"; // <- query parameter instead of query text modification
using (var query = new SqlCommand(query, con)) {
// bind query parameter with its actual value
query.Parameters.AddWithValue("#TimeIn", dtn);
// Just execute query, no reader
query.ExecuteNonQuery();
}
...
However, table Time as it appears in the question looks very strange, hardly does it contain TimeIn field only.
I am creating a project in which I need to run 2-3 SQL commands in a single SQL connection.
Here is the code I have written:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\project.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from " + mytags.Text + " ", con);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into " + mytags.Text + " values ('fname.lname#gmail.com','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+mytags.Text+"')", con);
cmd1.ExecuteNonQuery();
label.Visible = true;
label.Text = "Date read and inserted";
}
else
{
con.Close();
con.Open();
SqlCommand cmd2 = new SqlCommand("create table " + mytags.Text + " ( session VARCHAR(MAX) , Price int , Description VARCHAR(MAX), Date VARCHAR(20),tag VARCHAR(10))", con);
cmd2.ExecuteNonQuery();
con.Close();
con.Open();
SqlCommand cmd3 = new SqlCommand("insert into " + mytags.Text + " values ('" + Session + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + mytags.Text + "')", con);
cmd3.ExecuteNonQuery();
label.Visible = true;
label.Text = "tabel created";
con.Close();
}
I have tried to remove the error and I got that the connection is not going to else condition. Please review the code and suggest if there is any mistake or any other solution for this.
Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
The following should work. Keep single connection open all time, and just create new commands and execute them.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
Just enable this property in your connection string:
sqb.MultipleActiveResultSets = true;
This property allows one open connection for multiple datareaders.
I have not tested , but what the main idea is: put semicolon on each query.
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = #"
update table
set somecol = somevalue;
insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;
try
{
connection.Open();
}
finally
{
command.Dispose();
connection.Dispose();
}
Update:
you can follow
Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too
This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.
Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.
No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = #"update table ... where myparam=#myparam1 ; " +
"update table ... where myparam=#myparam2 ";
comm.Parameters.AddWithValue("#myparam1", myparam1);
comm.Parameters.AddWithValue("#myparam2", myparam2);
conn.Open();
comm.ExecuteNonQuery();
}
}
Multiple Non-query example if anyone is interested.
using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
DbConnection.Open();
using (OdbcCommand DbCommand = DbConnection.CreateCommand())
{
DbCommand.CommandText = "INSERT...";
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name";
DbCommand.ExecuteNonQuery();
DbCommand.Parameters.Clear();
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name2";
DbCommand.ExecuteNonQuery();
}
}
Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection
public static class SQLTest
{
public static void NpgsqlCommand()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
{
NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
command1.Connection.Open();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command2.Connection.Close();
}
}
}
using (var connection = new SqlConnection("Enter Your Connection String"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Enter the First Command Here";
command.ExecuteNonQuery();
command.CommandText = "Enter Second Comand Here";
command.ExecuteNonQuery();
//Similarly You can Add Multiple
}
}
It worked for me.