i have a program that insert a list of field into the database. When i use my own computer to insert the datetime field it looks completing fine. however, when i insert it using a windows 7 chinese edition, the field become 0000-00-00 00:00:00
this is the command
MySqlCommand myCommand4 = new MySqlCommand("Insert into OrderRecords_table values('" + OrderIDLabel.Text + "','" + customerCode + "','" + customer + "','" + TelComboBox.Text + "','" + LicenseComboBox.Text + "','" +
DriverComboBox.Text + "','" + AddressComboBox.Text + "','" + LocationTypeComboBox.Text + "','" + PickupComboBox.Text + "','" + CustomerTypeLabel.Text + "','" +
Convert.ToDecimal(TotalPriceLabel.Text) + "','" + status + "','" + note + "','" + sandReceiptNo + "','" + createtiming + "','" + Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) + "')", myConnection);
myCommand4.ExecuteNonQuery();
i know it looks a bit messy, but the part where it says
STR_TO_DATE('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','%Y/%M/%d /%H/%m/%s'))"
is the part where i insert the current datetime. it works just fine when i use english version of windows, but whenever i use chinese edition, it isnert 0000-00-00 00:00:00 instead of the actual time, i have tried to change the format for showing dates in control panel, but it is still having the same problem.
anyone knows what the problem would be ?
Thanks
edited my code
var sql = "insert into OrderRecords_table values(#OrderID, #customercode, #customer, #PhoneNumber, #license, #driver, #address, #type, #pickupLocation, #PaymentMethod, #totalPrice, #status, #notes, #sandreceiptNo,#createTime, #EditTime)";
using (var myCommand4 = new MySqlCommand(sql, myConnection))
{
myCommand4.Parameters.AddWithValue("#orderId", MySqlDbType.VarChar).Value = OrderIDLabel.Text;
myCommand4.Parameters.AddWithValue("#customercode", MySqlDbType.VarChar).Value = customerCode;
myCommand4.Parameters.AddWithValue("#customer",MySqlDbType.VarChar).Value = customer;
myCommand4.Parameters.AddWithValue("#PhoneNumber", MySqlDbType.VarChar).Value =TelComboBox.Text;
myCommand4.Parameters.AddWithValue("#license", MySqlDbType.VarChar).Value = LicenseComboBox.Text;
myCommand4.Parameters.AddWithValue("#driver", MySqlDbType.VarChar).Value = DriverComboBox.Text;
myCommand4.Parameters.AddWithValue("#address", MySqlDbType.VarChar).Value = AddressComboBox.Text;
myCommand4.Parameters.AddWithValue("#Type", MySqlDbType.VarChar).Value = LocationTypeComboBox.Text;
myCommand4.Parameters.AddWithValue("#pickupLocation", MySqlDbType.VarChar).Value = PickupComboBox.Text;
myCommand4.Parameters.AddWithValue("#PaymentMethod", MySqlDbType.VarChar).Value = CustomerTypeLabel.Text;
myCommand4.Parameters.AddWithValue("#totalPrice", MySqlDbType.Decimal).Value = Convert.ToDecimal(TotalPriceLabel.Text);
myCommand4.Parameters.AddWithValue("#status", MySqlDbType.VarChar).Value = status;
myCommand4.Parameters.AddWithValue("#notes", MySqlDbType.VarChar).Value =status;
myCommand4.Parameters.AddWithValue("#sandreceiptNo", MySqlDbType.VarChar).Value = sandReceiptNo;
myCommand4.Parameters.AddWithValue("#createTiming", MySqlDbType.DateTime).Value = createtiming;
myCommand4.Parameters.AddWithValue("#EditTime", MySqlDbType.DateTime).Value = DateTime.Now;
myCommand4.ExecuteNonQuery();
its saying that i have some invalid input, but i have checked a few times that all the fields are asigned to the correct type.. . don't know what is happening
I've rewritten your code to a more standardized implementation (with best practices). Note that I've pulled your query out into a separate variable to let the code and query become more readable.
var sql = "insert into orderrecords_table values " +
"(#orderId, " +
" #customercode, " +
" #customer, " +
" #telephone, " +
" #license, " +
" #driver, " +
" #address " +
" #locationType, " +
" #pickup, " +
" #customerType, " +
" #totalPrice, " +
" #status, " +
" #note, " +
" #sandreceiptNo, " +
" #createTiming, " +
" #currentTime) ";
using (var myCommand4 = new MySqlComm## Heading ##and(sql, connection))
{
myCommand4.Parameters.AddWithValue("#orderId", OrderIDLabel.Text) ;
myCommand4.Parameters.AddWithValue("#customercode", customerCode);
myCommand4.Parameters.AddWithValue("#customer", customer);
myCommand4.Parameters.AddWithValue("#telephone", TelComboBox.Text);
myCommand4.Parameters.AddWithValue("#license", LicenseComboBox.Text);
myCommand4.Parameters.AddWithValue("#driver", DriverComboBox.Text);
myCommand4.Parameters.AddWithValue("#address", AddressComboBox.Text);
myCommand4.Parameters.AddWithValue("#locationType", LocationTypeComboBox.Text);
myCommand4.Parameters.AddWithValue("#pickup", PickupComboBox.Text);
myCommand4.Parameters.AddWithValue("#customerType", CustomerTypeLabel.Text);
myCommand4.Parameters.AddWithValue("#totalPrice", Convert.ToDecimal(TotalPriceLabel.Text));
myCommand4.Parameters.AddWithValue("#status", status);
myCommand4.Parameters.AddWithValue("#note", status);
myCommand4.Parameters.AddWithValue("#sandreceiptNo", sandReceiptNo);
myCommand4.Parameters.AddWithValue("#createTiming", createtiming);
myCommand4.Parameters.AddWithValue("#currentTime", DateTime.Now);
myCommand4.ExecuteNonQuery();
}
MySqlCommand Insert = new MySqlCommand("INSERT INTO [TABLE] ([Date], [TEXT]) VALUES(#Date, #Text) ", myConnection);
Insert.CommandTimeout = 60; //if you need
Insert.Parameters.AddWithValue("#Date", DateTime.Now);
Insert.Parameters.AddWithValue("#Text", "Hello word!");
Insert.ExecuteNonQuery();
Insert.Dispose();
Related
here is the story :
Im trying to insert some data form the form to my data base but some thing wrong with the syntax "Vs Say so" but i can't find the mistake and some one help ?
MySqlConnection conn = new MySqlConnection("Server=localhost;Database=ltdb;UID=root;Password=1234;port=3306");
try
{
string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
conn.Open();
MySqlCommand cmd = new MySqlCommand(command, conn);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Saved !");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
INSERT INTO invoice companyName, ... missing opening brace, correct is
INSERT INTO invoice(column1, column2, ...) VALUES (#Columns1, #columns2, ...)
Coming to point 2: you're open for sql-injection. Use parameterized queries.
Change your
string command = "(INSERT INTO invoice companyName,rate,svatNo,tinNo,line1,line2,city)VALUES('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');";
To
string command = "INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES (#name,#rate,#vatno,#tinno,#adline1,#adline2,#city)";
command.Parameters.AddWithValue("name",txtname.Text);
command.Parameters.AddWithValue("rate",txtrate.Text);
....
*Edit: For more info, google "c# parameterized sql"
You put Wrong bracket
INSERT INTO invoice (companyName,rate,svatNo,tinNo,line1,line2,city) VALUES ('" + this.txtname.Text + "','" + this.txtrate.Text + "','" + this.txtsvatno.Text + "','" + this.txttinno.Text + "','" + txtadline1.Text + "','" + txtadline2.Text + "','" + txtcity.Text + "');
I have a table in mysql for users. Sometime user has a boss and sometime it don't.
So boss data type in nullable int(it is a foreign key, that's why nullable INT).
I was using following code and it was causing problem when boss value is null, producing following error "Incorrect integer value: '' for column 'boss_id' at row 1"
string query = " INSERT INTO " + databasename + ".system_user (" +
"`boss_id`, " +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Boss + "', '" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
MySqlConnection conDataBase = new MySqlConnection(myconnection);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
MySqlDataReader myreader;
try
{
conDataBase.Open();
myreader = cmdDataBase.ExecuteReader();
conDataBase.Close();
return true;
}
catch (Exception ex)
{
conDataBase.Close();
MessageBox.Show(ex.Message);
return false;
}
So, i changed the code for string query as follow:
string query = "";
if(systemuser.Boss!=null)
{
query = " INSERT INTO " + databasename + ".system_user (" +
"`boss_id`, " +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Boss + "', '" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
}
else
{
query = " INSERT INTO " + databasename + ".system_user (" +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
}
It worked because, Mysql by default put null at the skipped values.
Now according to my scenario, I have to update boss_id from int to null and sometime from null to int. But my query always skip if value is null. Can you please help me in changing the insert statement in such a way that it would insert null value in boos(if its null) and don't just skip it.
Firstly, you should use parameters, it gives you a clean code and avoid injection.
You can use parameters like this:
string query = string.Format("INSERT INTO {0}.system_user (`boss_id`, `name`, `user_name`, `password_2`, `designation`, `digital_signature`, `functional_role`, `group_2`)" +
"VALUES (#boss_id, #name, #user_name, #password_2, #designation, #digital_signature, #functional_role, #group_2)", databasename);
MySqlConnection conDataBase = new MySqlConnection(myconnection);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
cmdDataBase.Parameters.AddWithValue("#boss_id", systemuser.Boss ?? (object)DBNull.Value);
cmdDataBase.Parameters.AddWithValue("#name", systemuser.Name);
cmdDataBase.Parameters.AddWithValue("#user_name", systemuser.UserName);
cmdDataBase.Parameters.AddWithValue("#password_2", systemuser.Password);
cmdDataBase.Parameters.AddWithValue("#designation", systemuser.Designation);
cmdDataBase.Parameters.AddWithValue("#digital_signature", systemuser.DigitalSignature);
cmdDataBase.Parameters.AddWithValue("#functional_role", systemuser.FunctionalRole);
cmdDataBase.Parameters.AddWithValue("#group_2", systemuser.Group);
Note "#boss_id", systemuser.Boss ?? (object)DBNull.Value, this is because you can not use null directly in the parameters.
UPDATE:
If you want to update or delete you can use parameters too:
You can write your queries like this:
string query = string.Format("UPDATE {0}.system_user SET `name` = #name WHERE `boss_id` = #boss_id", databasename);
or
string query = string.Format("DELETE FROM {0}.system_user WHERE `boss_id` = #boss_id", databasename);
For datetime columns you can see this question. It has very good answers.
You are encapsulating the value of Systemuser.Boss in single quotes, doesn't this indicate that you are trying to insert a string into an integer column?
string query = #"INSERT INTO {0}.system_user (
`boss_id`,
`name`,
`user_name`,
`password_2`,
`designation`,
`digital_signature`,
`functional_role`,
`group_2`)
VALUES
{1},
'{2}',
'{3}',
'{4}',
'{5}',
'{6}',
'{7}',
'{8}')
";
string formattedQuery = string.Format(query,
databasename, // {0}
Systemuser.Boss, // {1}
Systemuser.Name, // {2}
etc, etc);
EDIT: missed a part where you said 'when it was null'... you need to use:
(Systemuser.Boss ?? "NULL")
I have an Access DB connected to my form with that code ( C# ) :
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB\DataMG.mdb";
try
{
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT into Prodotti ([Codice],[Descrizione],[Marchio],[Deposito],[Note],[NumeroProdotti],[PrzListinoBase_Aq],[PrzListinoBase_Ve],[Categoria],[Posizione],[Disponibilita],[QtaVenduta],[QtaAcquistata]) VALUES ('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "'," + this.Note.Text + "," + this.NumProd.Text + "," + this.PrzListAcq.Text + "," + this.PrzListVen.Text + ",'" + this.Categ.Text + "','" + this.Posiz.Text + "'," + this.Disp.Text + "," + this.QtaVen.Text + "," + this.QtaAcq.Text + ")";
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
// MessageBox.Show("Connessione Fallita!");
conn.Close();
}
finally
{
conn.Close();
}
The error I get when i click the buttton is this one :
Any ideas?
You are missing single quotations in Insert Statement where you are assigning values to columns. Your code is vulnerable so should avoid this here is a useful link.
Are Parameters really enough to prevent Sql injections?
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB \DataMG.mdb";
try
{
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT into Prodotti (Codice,Descrizione,Marchio,Deposito,Note,NumeroProdotti,PrzListinoBase_Aq,PrzListinoBase_Ve,Categoria,Posizione,Disponibilita,QtaVenduta,QtaAcquistata) VALUES('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "','" + this.Note.Text + "','" + this.NumProd.Text + "','" + this.PrzListAcq.Text + "','" + this.PrzListVen.Text + "','" + this.Categ.Text + "','" + this.Posiz.Text + "','" + this.Disp.Text + "','" + this.QtaVen.Text + "','" + this.QtaAcq.Text + "')";
conn.Open();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
// MessageBox.Show("Connessione Fallita!");
conn.Close();
}
finally
{
conn.Close();
}
I don't know italian (is that even the language? :) ) but from the look of it it could very well be a culture settings problem. If, for example, one of your fields is numeric then the database might expect a different decimal separator than the one in use in your UI.
Also your actual design seems very vulnerable to SQL Injection Attacks.
For these reasons, my suggestion is that you use the command's Parameters collection to set your values rather than trying to pass in a concatenated string.
I don't read the language you are posting the error from, however, it looks like a syntax error somewhere in your SqlCommand.
First thing I would suggest is wrapping your connection and command in using blocks to make sure they get disposed of correctly.
Then ALWAYS user parametarized SQL Commands to avoid SQL Injection:
using (var conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB\DataMG.mdb"))
using (var cmd = new System.Data.OleDb.OleDbCommand())
{
cmd.CommandText = "INSERT INTO TableName (column1, column2, column3) VALUES (#Value1, #Value2, #Value3)";
cmd.Parameters.AddWithValue("#Value1", this.TextBox1.Text);
cmd.Parameters.AddWithValue("#Value2", this.TextBox2.Text);
cmd.Parameters.AddWithValue("#Value3", this.TextBox3.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
Generally speaking, using parameters eliminates syntax errors because it makes the command much easier to read in it's string representation.
I think you may be missing single quotes around some of your text qualifiers in your INSERT statement.
"INSERT into Prodotti ([Codice],[Descrizione],[Marchio],[Deposito],[Note],[NumeroProdotti],[PrzListinoBase_Aq],[PrzListinoBase_Ve],[Categoria],[Posizione],[Disponibilita],[QtaVenduta],[QtaAcquistata]) VALUES ('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "'," + this.Note.Text + "," + this.NumProd.Text + "," + this.PrzListAcq.Text + "," + this.PrzListVen.Text + ",'" + this.Categ.Text + "','" + this.Posiz.Text + "'," + this.Disp.Text + "," + this.QtaVen.Text + "," + this.QtaAcq.Text + ")";
Consider using a parameterized query rather than building your query string by hand. Not only is it safer, but it can help to weed out these kinds of errors which can be tedious to debug.
eg.
String StrSQL = "INSERT INTO tblLog ([Part_Number],[Quantity],[Date],[LOC_Warehouse],[LOC_Row],[LOC_Section],[LOC_Level],[LOC_Bin],[Stock_Added],[Stock_Removed],[Quarantine_Set],[Quarantine_Removed])"
+ "VALUES(#Part_Number, #Quantity, #Date, #Warehouse, #Row, #Section, #Level, #Bin, #Stock_Added, #Stock_Removed, #Quarantine_Set, #Quarantine_Removed)";
SqlConnection conn = new SqlConnection(WHITS.Properties.Settings.Default.LocalConnStr);
SqlCommand cmd = new SqlCommand(StrSQL, conn);
cmd.Parameters.AddWithValue("#Part_Number", Part_Number);
cmd.Parameters.AddWithValue("#Quantity", Quantity);
cmd.Parameters.AddWithValue("#Date", DateTime.Now);
//More Parameters... Skipped for brevity.
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Open your connection earlier. Also, use "using". Here's how I would do it:
try
{
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_20_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB\DataMG.mdb";
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString))
{
conn.Open();
string insertQuery = "INSERT into Prodotti ([Codice],[Descrizione],[Marchio],[Deposito],[Note],[NumeroProdotti],[PrzListinoBase_Aq],[PrzListinoBase_Ve],[Categoria],[Posizione],[Disponibilita],[QtaVenduta],[QtaAcquistata]) VALUES ('" + this.Codice.Text + "','" + this.Descr.Text + "','" + this.Marchio.Text + "','" + this.Deposito.Text + "'," + this.Note.Text + "," + this.NumProd.Text + "," + this.PrzListAcq.Text + "," + this.PrzListVen.Text + ",'" + this.Categ.Text + "','" + this.Posiz.Text + "'," + this.Disp.Text + "," + this.QtaVen.Text + "," + this.QtaAcq.Text + ")";
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(insertQuery, conn);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
}
}
Edit: My bad... the code I was referencing was filling a DataAdapter, which doesn't require a call to connection.Open(). Regular querying does. My apologies... I have edited my suggestion.
There is problem in this code when I use parameterized query loop get one file name in string filename = Path.GetFileName(item); variable again and again
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + newtable));
int a = 0;
OleDbCommand cmd = new OleDbCommand();
OleDbConnection mycon = new OleDbConnection();
mycon.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb";
cmd = mycon.CreateCommand();
mycon.Open();
DateTime dateTime = DateTime.UtcNow.Date;
foreach (string item in filePaths)
{
a++;
string filename = Path.GetFileName(item);
string ips = "00" + a.ToString();
// Response.Write("Number (" + a.ToString() + ") " + filename + " " + ips + " " + t1 + " " + v + " " + some + " " + some + "<br/><br/>");
// cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES('" + filename + "','" + ips + "','" + dateTime.ToString("dd/MM/yyyy") + "','" + newtable + "','" + TextBox4.Text + "','" + TextBox3.Text + "')";
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES (?,?,?,?,?,?)";
cmd.Parameters.AddWithValue("#p1", filename);
cmd.Parameters.AddWithValue("#p2", ips);
cmd.Parameters.AddWithValue("#p3", dateTime.ToString("dd/MM/yyyy"));
cmd.Parameters.AddWithValue("#p4", newtable);
cmd.Parameters.AddWithValue("#p5", TextBox4.Text);
cmd.Parameters.AddWithValue("#p6", TextBox3.Text);
cmd.ExecuteNonQuery();
}
But when I use normal insert query
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES('" + filename + "','" + ips + "','" + dateTime.ToString("dd/MM/yyyy") + "','" + newtable + "','" + TextBox4.Text + "','" + TextBox3.Text + "')";
loop is working alright and get all the name of files at specific location. Please let me know why ?Is there any problem in my logic ?
cmd.Parameters collection is not cleared between iterations. You should create parameters before the loop and set values in the loop, instead of using AddWithValue
cmd = mycon.CreateCommand();
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES (?,?,?,?,?,?)";
cmd.Parameters.Add('#p1',...);
...same for other params...
mycon.Open();
DateTime dateTime = DateTime.UtcNow.Date;
foreach (string item in filePaths)
{
a++;
string filename = Path.GetFileName(item);
string ips = "00" + a.ToString();
cmd.Parameters["#p1"].Value = filename;
...same for other params...
cmd.ExecuteNonQuery();
}
However you can just add cmd.Parameters.Clear() after cmd.ExecuteNonQuery() :)
As it noted in MSDN
OleDbParameterCollection.AddWithValue Method
Adds a value to the end of the OleDbParameterCollection
So engine doesn't see #p1 added on the second iteration because it already found #p1 added on the first one.
When I insert data using a SqlCommand, It also add space before values which I just inserted. How do I avoid adding spaces?
Here is the insert query code:
SqlCommand cmd1 = new SqlCommand("INSERT INTO [Contracts].[dbo].[Contract]
([Contract_Id],[Name],[Description],[Contracted_by],[Vendor_Name],[Related_Dept],[Start_date],[Expiration_Date],[TypeofContract],[Contact_Person],[Contact_No],FileName,FileData,FileType)
VALUES (' " + TextBox1.Text + "',' " + TextBox2.Text + "',' " + TextBox3.Text + "',' " + TextBox4.Text + "',' " + TextBox5.Text + "',' " + DepartmentTextBox.SelectedValue.ToString() + "',' " + TextBox7.Text + "',' " + TextBox8.Text + "',' " + TextBox9.Text + "',' " + TextBox10.Text + "',' " + TextBox11.Text + "',#Name,#Data,#Type)", con);
Of course any kind of problems surface when you use string concatenation to build command text. In your case you have inadvertently added a space before your control values.
If you had used a parameterized query this problem would not have arisen
SqlCommand cmd1 = new SqlCommand("INSERT INTO [Contracts].[dbo].[Contract] " +
"([Contract_Id],[Name],[Description],[Contracted_by],[Vendor_Name],[Related_Dept]," +
"[Start_date],[Expiration_Date],[TypeofContract],[Contact_Person]," +
"[Contact_No],FileName,FileData,FileType) VALUES (" +
"#cid, #name, #desc, #cby, #vname, #rdept, #stdate, #expdate, " +
"#tc, #cp, #cno, #file, #fdate, #ftype",con)
SqlParameter p = new SqlParameter("#cid", SqlDbType.Int).Value = Convert.ToInt32(textBox1.Text));
cmd.Parameters.Add(p);
.... and so on for the other parameters required
By the way, remember that if you have an IDENTITY column you should not try to insert anything in that column (Contract_ID is particulary suspect here)
It's inserting spaces because you have extra spaces in your query string. I changed "',' " to "','":
SqlCommand cmd1 = new SqlCommand("INSERT INTO [Contracts].[dbo].[Contract] ([Contract_Id],
[Name],[Description],[Contracted_by],[Vendor_Name],[Related_Dept],[Start_date],
[Expiration_Date],[TypeofContract],[Contact_Person], Contact_No],FileName,FileData,FileType)
VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" +
TextBox4.Text + "','" + TextBox5.Text + "','" + DepartmentTextBox.SelectedValue.ToString()
+ "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" +
TextBox10.Text + "','" + TextBox11.Text + "',#Name,#Data,#Type)", con);