Foreach Loop is not Working properly - c#

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.

Related

how to save imported excel in datagridview to database C#

how to save imported data from excel in datagridview to database in C#
I have saved records and exported to excel sheet, it exported along with data ID, now I have re-imported back to datagridview from excel. now I want to save data to database.
Important to know:
Database name "Records.sdf" using SQL Compact 3.5
DataGridViewName is RecordsDataGridView.
I'm using following code but it's not working.
public void SaveData()
{
// Save the data.
SqlCeConnection conn =
new SqlCeConnection(
#"Data Source=|DataDirectory|\Records.sdf;Persist Security Info=False");
SqlCeCommand com;
string str;
conn.Open();
for (int index = 0; index < RecordsDataGridView.Rows.Count - 1; index++)
{
str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values(" + RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ", '" + RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "'," + RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + "," + RecordsDataGridView.Rows[index].Cells[8].Value.ToString() + ")";
com = new SqlCeCommand(str, conn);
com.ExecuteNonQuery();
}
conn.Close();
}
ERROR RECEIVING
Column Name not Valid, column name = Cash
Try this query string
str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values(" + RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ",'"+ RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "'," + RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + ",'" + RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + "','" + RecordsDataGridView.Rows[index].Cells[8].Value.ToString() + "')";
You should pass varchar field enclosed with single quote.
var str = #"Insert Into OutgoingChequeRecords(ID,BankName,Date,AccountNo, Chequebook, ChequeNo, Payee, Amount, Remarks) Values("
+ RecordsDataGridView.Rows[index].Cells[0].Value.ToString() + ", '"
+ RecordsDataGridView.Rows[index].Cells[1].Value.ToString() + "',"
+ RecordsDataGridView.Rows[index].Cells[2].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[3].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[4].Value.ToString() + ","
+ RecordsDataGridView.Rows[index].Cells[5].Value.ToString() + ","
+ "'" + RecordsDataGridView.Rows[index].Cells[6].Value.ToString() + "'" + ","
+ RecordsDataGridView.Rows[index].Cells[7].Value.ToString() + ","
+ "'" + dataGridView1.Rows[index].Cells[8].Value.ToString() + "'" + ")";
There are a few ways to do this.
Here is one method.
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
http://csharp.net-informations.com/datagridview/csharp-datagridview-database-operations.htm
You can do this as well.
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= #"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
Something like this will work too.
private void buttonSave_Click_1(object sender, EventArgs e) // save to invoice
{
SqlConnection con = new SqlConnection(MyConnectionString);
string SqlCmdText = "INSERT INTO invoice (p_code, p_name, p_category, p_price) " +
VALUES (#code, #name, #category, #price)";
SqlCommand sc = new SqlCommand(SqlCmdText, con);
con.Open();
foreach (DataRow row in MyTable.Rows)
{
sc.Parameters.Clear();
sc.Parameters.AddWithValue("#code", row["p_code"]);
sc.Parameters.AddWithValue("#name", row["p_name"]);
sc.Parameters.AddWithValue("#category", row["p_category"]);
sc.Parameters.AddWithValue("#price", row["p_price"]);
sc.ExecuteNonQuery();
}
con.Close();
}

If combobox not selected any item enter empty string into Access database

When I enter a data in my Access database, if I do not select any item in the combobox, I get an error of null exception. So how can I make sure that if I did not select any items, empty data is inserted into my database?
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
if (comboBox10.SelectedItem == null)
{
comboBox10.Text = " ";
}
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10.SelectedItem.ToString() + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();
You can check if the SelectedItem property is null, then set a temp variable to use in your query string.
string comboBox10Text = comboBox10.SelectedItem == null ? String.Empty : comboBox10.Text;
Then use comboBox10Text in your query string.
Edit:
// Check if comboBox10.SelectedItem is null, set temp variable
string comboBox10Text = comboBox10.SelectedItem == null ? String.Empty : comboBox10.Text;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
// Update query string to use comboBox10Text instead of accessing SelectedItem
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10Text + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();
You can have a null check and change the condition
If(comboBox10.SelectedItem != null)
{
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10.SelectedItem.ToString() + "')";
}
else
{
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + "" + "')";
}

c# mysqlcommnand insert into mysql database

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();

Insert record(s) DB from Form

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.

i'm trying to insert to the data base but i have an error called overflow

this is the code
public static void ChangeTable(string strSql, string FileName)
{
OleDbConnection c = MakeConnection(FileName);
OleDbCommand comm = new OleDbCommand();
comm.CommandText = strSql;
comm.Connection = c;
comm.ExecuteNonQuery();
c.Close();
}
strSql = "Insert into h3rot(name,lastname,tlfon,nyad,email,brodcuts)" +
" VALUES(
'
" +
TextBox1.Text +
"','" +
TextBox2.Text +
"'," +
phone +
"," +
pel +
",'" +
TextBox5.Text +
"','" +
DropDownList1.Text + "
')";
1) your code is SCREAMING out "sql injection" so you should REALLY be doing something to sanitize all of those textboxes. And you should at least be using parameter markers instead of just appending strings together.
2) you've probably exceeded the size of one of the columns in your database. without more information about what was in the textboxes or the schema of the database, there's not much else to say.
try DropDownList1.SelectedValue

Categories

Resources