Hello I want to store datetimepicker value into mysql database my code is given below
dtpDate = datetimepicker1.value.date;
dtpTime = datetimepicker2.value.Timeofday;
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ('" + name + "','" + dtpTime + "','" + s + "','" + day + "','"+dtpDate+"','" + chkArray[i].Tag + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
but no value is being stored at database
and at that place there is unable to read data comes.
what may be the problem?
The Value is not being entered at MySQL database because there is mistake in your query at dtpTime and dtpDate fields.
you shout replace it whith dtpTime.Value.TimeofDay and dtpDate.Value.Date ane new query will be like this
dtpDate = datetimepicker1.value.date;
dtpTime = datetimepicker2.value.Timeofday;
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ('" + name + "','" + dtpTime.Value.TimeofDay + "','" + s + "','" + day + "','"+dtpDate.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','" + chkArray[i].Tag + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Well, it may not be the cause of the problem (are there any exceptions? What does ExecuteNonQuery return?) but you should definitely not be building up your SQL like this. It leads to SQL injection attacks, as well as data conversion problems.
Instead, you should use parameterized SQL:
using (MySqlConnection conn = new MySqlConnection(...))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(
"INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) " +
"VALUES (#name, #time, #status, #days, #date, #connector)", conn))
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = name;
cmd.Parameters.Add("#time", MySqlDbType.Time).Value = dtpTime;
cmd.Parameters.Add("#status", MySqlDbType.VarChar).Value = s;
cmd.Parameters.Add("#days", MySqlDbType.Int32).Value = day;
cmd.Parameters.Add("#date", MySqlDbType.Date).Value = dtpDate;
cmd.Parameters.Add("#connector", MySqlDbType.VarChar).Value = chkArray[i].Tag;
int insertedRows = cmd.ExecuteNonQuery();
// TODO: Validate that insertedRows is 1?
}
}
I've guessed at the data types - please check them against your actual database.
Using NuGet Package MySql.Data 6.6.4.
Currently MySqlParameter does not support unnamed parameters. Parameters must begin with with a ?.
Example:
command.Parameters.AddWithValue("?Parameter", value);
Something like this should work. Avoid string concatenation with Sql because that can lead to security risks.
dtpDate = datetimepicker1.value.date.ToString("yyyy-MM-dd HH:mm"); //Formatted Date for MySql
dtpTime = datetimepicker2.value.Timeofday;
using(var connection = new MySqlConnection(connectionString))
{
using(var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ( ?ScheduleName, ?StartTime, ?Status, ?Days, ?StartDate, ?ConnectorId )";
command.Parameters.AddWithValue("?ScheduleName", name);
command.Parameters.AddWithValue("?StartTime", dtpTime);
command.Parameters.AddWithValue("?Status", s);
command.Parameters.AddWithValue("?Days", day);
command.Parameters.AddWithValue("?StartDate", dtpDate);
command.Parameters.AddWithValue("?ConnectorId", chkArray[i].Tag);
connection.Open();
command.ExecuteNonQuery();
}
}
Related
The problem says:
Too few parameters. Expected 1.
Here's my database table:
CustomerOrder [CustomerOrder(OrderId, ProdName, ProdPrice, OrderQty, CatName, OrderDate]
Code:
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO CustomerOrder(OrderId, ProdName, ProdPrice, OrderQty, CatName, OrderDate)values('" + txtOrderCode.Text + "','" + txtProdName.Text + "', '" + txtProdPrice.Text + "', '" + txtOrderQty.Text + "', '" + txtCatName.Text + "', '" + txtOrderDate.Text + "')";
cmd.ExecuteNonQuery();
tabControl1.SelectedTab = tabPage1;
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
int ordercode, orderqty;
double price;
string prodname, catname;
ordercode = Convert.ToInt32(txtOrderCode.Text);
orderqty = Convert.ToInt32(txtOrderQty.Text);
price = Convert.ToDouble(txtProdPrice.Text);
prodname = Convert.ToString(txtProdName.Text);
I would recommend you use parametrised queries instead as it will prevent you from Sql Injection Attacks. Here is a small example of how it could work with your code
String SqlCommand = "insert into CUSTOMERORDER values (#OrderId, #ProdName,#ProdPrice,#OrderQty, #CatName,#OrderDate)";
SqlCommand cmd = new SqlCommand(SqlCommand , //ConnectionString);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.Parameters.AddWithValue("#OrderId", txtOrderCode.Text);
cmd.Parameters.AddWithValue("#ProdName", txtProdName.Text );
cmd.Parameters.AddWithValue("#ProdPrice", txtProdPrice.Text);
cmd.Parameters.AddWithValue("#OrderQty", txtOrderQty.Text);
cmd.Parameters.AddWithValue("#CatName", txtCatName.Text.Text);
cmd.Parameters.AddWithValue("#OrderDate", txtOrderDate.Text);
cmd.ExecuteNonQuery();
conn.Close();
Read up on Sql Injection attacks. Doing it this way is much easier, cleaner and most importantly, safer. Also when looking at your code you are setting the text box values after you have ran the Sql command
how to insert the current time using ado.net sql command. getting error saying The "conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
code
DateTime NowTime = DateTime.Now;
string usecase = "manhole";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
con.Open();
SqlCommand cmdInsert = new SqlCommand("insert into sms values('" + usecase + "','" + smsbody + "','" + NowTime + "')", con);
try
{
cmdInsert.ExecuteNonQuery();
}
columns
updtd_date is datetime
query
INSERT INTO sms (usecase, sms, updtd_date)
VALUES ('manhole','level is low at : 22/01/2018 15:56:20','22/01/2018 16:18:28');
You should use a parametized query instead of concatenating strings, what you are doing is asking for an SQL Injection. Also, you should dispose commands and connections after use them in order to release memory.
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
{
using (var command = new SqlCommand("insert into sms (col1) values(#col1"))
{
command.Parameters.AddWithValue("#col1", DateTime.Now);
con.Open();
command.ExecuteNonQuery();
}
}
Use The Function GETDATE() To Get the System Date and Time.
Change NowTime
"insert into sms values('" + usecase + "','" + smsbody + "','" + NowTime + "')"
To This
"insert into sms values('" + usecase + "','" + smsbody + "',GETDATE())"
Executing the SQL Statements Like this Can Cause SQL Injection, So I Recommend using Parameter may Be Something Like this
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("insert into sms values(#usecase,#smsbody,GETDATE())", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#usecase", SqlDbType.VarChar).Value = usecase;
cmd.Parameters.Add("#smsbody", SqlDbType.VarChar).Value = smsbody;
con.Open();
cmd.ExecuteNonQuery();
}
}
I think you need to be specific with the date format in SQL if you inserting a date if you not using paramater:
string nowDate = DateTime.Now.ToString("dd MMM yyy HH:mm:ss");
string sql = "insert into #dateT values('"+nowDate+"')";
This results to this in my pc
insert into #dateT values('22 Jan 2018 13:27:04');
i have a button that when clicked inserts data from textbox and combobox fields into database tables, but every time i insert it gives me "Invalid attempt to call read when reader is closed". How can i get rid of this error. And tips on optimising the code are welcome, because i know im a total noob. thanks
private void btnSave_Click(object sender, RoutedEventArgs e)
{
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query1 = "insert into location(Storage, Shelf, columns, rows) values(" + txtWarehouse.Text + ", " + txtShelf.Text + ", " + txtColumn.Text + ", " + txtRow.Text + ")";
SqlCommand sqlCmd = new SqlCommand(Query1, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
sqlCon.Close();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
try
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb; Initial Catalog=Storagedb;");
sqlCon.Open();
string Query3 = "SELECT LOCATION_ID FROM LOCATION WHERE storage='" + txtWarehouse.Text + "' AND shelf='" + txtShelf.Text + "' AND columns='"
+ txtColumn.Text + "' AND rows='" + txtRow.Text + "'";
SqlCommand sqlCmd1 = new SqlCommand(Query3, sqlCon);
SqlDataReader dr = sqlCmd1.ExecuteReader(); ;
while (dr.Read())
{
string LocationId = dr[0].ToString();
dr.Close();
string Query2 = "insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID) values ('" + txtSku.Text + "','" + txtNimetus.Text + "', '"
+ txtMin.Text + "', '" + txtMax.Text + "', '" + txtQuan.Text + "', '" + LocationId + "', '" + (cbCat.SelectedIndex+1) + "', '" + (cbMail.SelectedIndex+1) + "')";
SqlCommand sqlCmd = new SqlCommand(Query2, sqlCon);
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlCmd);
dataAdp.SelectCommand.ExecuteNonQuery();
}
sqlCon.Close();
}
catch (Exception ed)
{
MessageBox.Show(ed.Message);
}
}
Let's try to make some adjustments to your code.
First thing to consider is to use a parameterized query and not a
string concatenation when you build an sql command. This is mandatory
to avoid parsing errors and Sql Injections
Second, you should encapsulate the disposable objects in a using statement
to be sure they receive the proper disposal when you have finished to
use them.
Third, you can get the LOCATION_ID from your table without running a
separate query simply adding SELECT SCOPE_IDENTITY() as second batch to your first command. (This works only if you have declared the LOCATION_ID field in the first table as an IDENTITY column)
Fourth, you put everything in a transaction to avoid problems in case
some of the code fails unexpectedly
So:
SqlTransaction tr = null;
try
{
string cmdText = #"insert into location(Storage, Shelf, columns, rows)
values(#storage,#shelf,#columns,#rows);
select scope_identity()";
using(SqlConnection sqlCon = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, sqlCon))
{
sqlCon.Open();
using( tr = sqlCon.BeginTransaction())
{
// Prepare all the parameters required by the command
cmd.Parameters.Add("#storage", SqlDbType.Int).Value = Convert.ToInt32(txtWarehouse.Text);
cmd.Parameters.Add("#shelf", SqlDbType.Int).Value = Convert.ToInt32(txtShelf.Text);
cmd.Parameters.Add("#columns", SqlDbType.Int).Value = Convert.ToInt32(txtColumn.Text );
cmd.Parameters.Add("#rows", SqlDbType.Int).Value = Convert.ToInt32(txtRow.Text);
// Execute the command and get back the result of SCOPE_IDENTITY
int newLocation = Convert.ToInt32(cmd.ExecuteScalar());
// Set the second command text
cmdText = #"insert into product(SKU, nimetus, minimum, maximum, quantity,location_ID,category_ID,OrderMail_ID)
values (#sku, #nimetus,#min,#max,#qty,#locid,#catid,#ordid)";
// Build a new command with the second text
using(SqlCommand cmd1 = new SqlCommand(cmdText, sqlCon))
{
// Inform the new command we are inside a transaction
cmd1.Transaction = tr;
// Add all the required parameters for the second command
cmd1.Parameters.Add("#sku", SqlDbType.NVarChar).Value = txtSku.Text;
cmd1.Parameters.Add("#nimetus",SqlDbType.NVarChar).Value = txtNimetus.Text;
cmd1.Parameters.Add("#locid", SqlDbType.Int).Value = newLocation;
.... and so on for the other parameters required
cmd1.ExecuteNonQuery();
// If we reach this point the everything is allright and
// we can commit the two inserts together
tr.Commit();
}
}
}
}
catch (Exception er)
{
// In case of exceptions do not insert anything...
if(tr != null)
tr.Rollback();
MessageBox.Show(er.Message);
}
Notice that in the first command I use parameters of type SqlDbType.Int because you haven't used single quotes around your text. This should be verified against the real data type of your table columns and adjusted to match the type. This is true as well for the second command where you put everything as text albeit some of those fields seems to be integer (_location_id_ is probably an integer). Please verify against your table.
The below is my code to insert gridview data into a database. However, using this I want to check and restrict insertion into the database where records have the same name, location, education and salary. If all of these are the same and those already present in database they should not get inserted. If any one column is different then they should get inserted.
protected void btn_insert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert command", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
UploadStatusLabel.Text = "Records Inserted Successfully";
}
I think hitting the database inside a for loop is a very bad idea when you have other options. I'm not tackling this issue in the below sample.
Your code may be subject to SQL Injection, you need to use parameters to pass your values. If someone filled the input with ";DROP TABLE OpenOfficetext;" and they have DROP permissions, it will be a problem if you're just concatenating strings.
To avoid duplicates, you can check first if a similar record exists.
foreach (GridViewRow g1 in GridView1.Rows)
{
string insertCommand = "insert into OpenOfficetext(Name, Location, Education, Salary) values(#p1, #p2, #p3, #p4)";
string selectCommand = "SELECT COUNT(*) FROM OpenOfficetext WHERE Name = #p1 AND Location = #p2 AND Education = #p3 AND Salary = #p4";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(selectCommand, con);
con.Open();
cmd.Parameters.AddWithValue("#p1", g1.Cells[0].Text);
cmd.Parameters.AddWithValue("#p2", g1.Cells[1].Text);
cmd.Parameters.AddWithValue("#p3", g1.Cells[2].Text);
cmd.Parameters.AddWithValue("#p4", g1.Cells[3].Text);
if (Convert.ToInt32(cmd.ExecuteScalar()) == 0)
{
cmd.CommandText = insertCommand;
cmd.ExecuteNonQuery();
}
con.Close();
}
please use the below code
if not exist (select * from OpenOfficetext where Name='" + g1.Cells[0].Text + "' and Location='" + g1.Cells[1].Text + "' and Education = '" + g1.Cells[2].Text + "' and Salary = '" + g1.Cells[3].Text + "' )
Begin
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert into OpenOfficetext(Name,Location,Education,Salary) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
End
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.