I cant insert data into my DB - c#

I'm trying to insert data into my DB and when i press the button it should get done but it won't
I guess it's from my last layer somewhere in my Query
here's my code
public void InsertInventory(DateTime _date, int _customer_Id,
int _employee_Id, List<int> _product_Id,
List<int> _amountSold,
List<int> _unitPrice, List<int> _totalPrice)
{
Connection_String = #"Data Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=TrueData Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=True;";
Query = "insert into Inventory" +
"(Customer_Id,Employee_Id,Product_Id,[Date],[Amount Sold],[Unit Price],[Total Price])" +
"values (#customer_id,#Employee_id,#Product_id,#[Date],#[Amount_Sold],#[Unit_Price],#[Total_Price])";
using (Con = new SqlConnection(Connection_String))
using (Cmd = new SqlCommand(Query, Con))
{
Cmd.Parameters.Add("#customer_id", SqlDbType.Int);
Cmd.Parameters.Add("#Employee_id", SqlDbType.Int);
Cmd.Parameters.Add("#Product_id", SqlDbType.Int);
Cmd.Parameters.Add("#[Date]", SqlDbType.NVarChar);
//Cmd.Parameters.Add("#[Date]", SqlDbType.Date);
Cmd.Parameters.Add("#[Amount_sold]", SqlDbType.Int);
Cmd.Parameters.Add("#[Unit_Price]", SqlDbType.Decimal);
Cmd.Parameters.Add("#Total_Price", SqlDbType.Decimal);
Cmd.Connection = Con;
Con.Open();
int RecordToAdd = _product_Id.Count;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#Product_id"].Value = _product_Id;
Cmd.Parameters["#Date"].Value = _date;
Cmd.Parameters["#Amount_sold"].Value = _amountSold;
Cmd.Parameters["#Unit_Price"].Value = _unitPrice;
Cmd.Parameters["#Total_Price"].Value = _totalPrice;
Cmd.ExecuteNonQuery();
}
}
}
I can't figure it out where my problem is

The problem is caused by the values that you set for your parameters.
You should use the indexer to retrieve an element from the lists not the whole lists
// These doesn't change inside the loop, so set it once for all...
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#Date"].Value = _date;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#Product_id"].Value = _product_Id[i];
Cmd.Parameters["#Amount_sold"].Value = _amountSold[i];
Cmd.Parameters["#Unit_Price"].Value = _unitPrice[i];
Cmd.Parameters["#Total_Price"].Value = _totalPrice[i];
Cmd.ExecuteNonQuery();
}

Related

issue with fetching value from 2md datagridview in c#

i have a problem in fetching value from data gridview. In the same event i am able to fetch value from datagrid view1 but in same event i am not able to fetch the value from datagridview2. Help me with correction in following code.
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(path);
SqlConnection con1 = new SqlConnection(path);
con.Open();
string selectSql = "select * from textbooks where class='" + txt_class.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(selectSql, con);
string textname = "";
tempcnt.Text = "test";
string bookname = "";
double bookquantity = 0;
string textname1 = "";
string bookname1 = "";
double stockquantity1 = 0;
double bookquantity1 = 0;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
bookname = (reader["name"].ToString());
bookquantity = Convert.ToInt32(reader["quantity"]);
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
textname = Convert.ToString(dataGridView1.Rows[i].Cells[0].Value);
if (textname == bookname)
{
bookquantity = bookquantity - 1;
temp_count.Text = bookquantity.ToString();
con1.Open();
string uquery = "update textbooks set quantity=" + bookquantity + " where name='" + bookname + "'";
SqlCommand cmd1 = new SqlCommand(uquery, con1);
cmd1.ExecuteNonQuery();
con1.Close();
}
}
}
}
con.Close();
con.Open();
string selectSql2 = "select * from notebooks";
SqlCommand cmd2 = new SqlCommand(selectSql2, con);
tempcnt.Text = "test";
using (SqlDataReader reader1 = cmd2.ExecuteReader())
{
while (reader1.Read())
{
bookname1 = (reader1["name"].ToString());
stockquantity1 = Convert.ToInt32(reader1["quantity"]);
tempcnt.Text = bookname1;
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
textname1 = dataGridView2.Rows[i].Cells[0].Value as string;
string temp = Convert.ToString(dataGridView2.Rows[i].Cells[0].Value);
tempcnt.Text = temp;
if (temp == bookname1)
{
tempcnt.Text = "success";
}
}
}
}
con.Close();
}

Failed trying to insert my data

I'm trying to insert some list into my Data base(Microsoft) but i got this run time error
Failed to convert parameter value from a List`1 to a Int32.
here's my code
public void InsertInventory(DateTime _date, int _customer_Id,
int _employee_Id, List<int> _product_Id,
List<int> _amountSold,
List<int> _unitPrice, List<int> _totalPrice)
{
Connection_String = #"Data Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=TrueData Source=MOSTAFA-PC;Initial Catalog="
+ "Sales and Inventory System"
+ ";Integrated Security=True;";
Query = "insert into Inventory" +
"(Customer_Id,Employee_Id,Product_Id,[Date],[Amount Sold],[Unit Price],[Total Price])" +
"values (#customer_id,#Employee_id,#Product_id,#[Date],#[Amount_Sold],#[Unit_Price],#[Total_Price])";
using (Con = new SqlConnection(Connection_String))
using (Cmd = new SqlCommand(Query, Con))
{
Cmd.Parameters.Add("#customer_id", SqlDbType.Int);
Cmd.Parameters.Add("#Employee_id", SqlDbType.Int);
Cmd.Parameters.Add("#Product_id", SqlDbType.Int);
//Cmd.Parameters.Add("#[Date]", SqlDbType.NVarChar);
Cmd.Parameters.Add("#[Date]", SqlDbType.Date);
Cmd.Parameters.Add("#[Amount_sold]", SqlDbType.Int);
Cmd.Parameters.Add("#[Unit_Price]", SqlDbType.Decimal);
Cmd.Parameters.Add("#Total_Price", SqlDbType.Decimal);
Cmd.Connection = Con;
Con.Open();
int RecordToAdd = _product_Id.Count;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#Product_id"].Value = _product_Id;
Cmd.Parameters["#[Date]"].Value = _date;
Cmd.Parameters["#[Amount_sold]"].Value = _amountSold;
Cmd.Parameters["#[Unit_Price]"].Value = _unitPrice;
Cmd.Parameters["#Total_Price"].Value = _totalPrice;
Cmd.ExecuteNonQuery();
}
i searched the web sites but i couldn't find any thing usefull or similar to my problem
What should i do?
change this:
int RecordToAdd = _product_Id.Count;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#Product_id"].Value = _product_Id;
Cmd.Parameters["#[Date]"].Value = _date;
Cmd.Parameters["#[Amount_sold]"].Value = _amountSold;
Cmd.Parameters["#[Unit_Price]"].Value = _unitPrice;
Cmd.Parameters["#Total_Price"].Value = _totalPrice;
Cmd.ExecuteNonQuery();
}
To this:
int RecordToAdd = _product_Id.Count;
for (int i = 0; i < RecordToAdd; i++)
{
Cmd.Parameters["#customer_id"].Value = _customer_Id;
Cmd.Parameters["#Employee_id"].Value = _employee_Id;
Cmd.Parameters["#Product_id"].Value = _product_Id[i];
Cmd.Parameters["#[Date]"].Value = _date;
Cmd.Parameters["#[Amount_sold]"].Value = _amountSold[i];
Cmd.Parameters["#[Unit_Price]"].Value = _unitPrice[i];
Cmd.Parameters["#Total_Price"].Value = _totalPrice[i];
Cmd.ExecuteNonQuery();
}
Notice in the second block I'm using the iterator of the loop to index which item in the list I'm inserting each time.
EDIT: Also, that connection_string you built doesn't look right. You might want to review it and correct any mistakes
Change the "List<>" in FUNCTION PARAMETERS for Int32 or Integer.

How to update and delete data without a few words from text file

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);
}
}
}
}
}**

How do multi rows insert with MySqlCommand and prepare statement?(#C)

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

Convert InnerHtml values into Decimal

Im trying to convert InnerHtml values to Decimal value. The user will input an XPath into textBox2
List<Decimal> productPriceList = new List<Decimal>();
var priceTags = document.DocumentNode.SelectNodes(textBox2.Text);
Then I do a foreach loop to iterate though the prices found and add them to a list called productPriceList
foreach (var prices in priceTags)
{
label9.Visible = true;
label9.Text += prices.InnerHtml + "\n";
productPriceList.Add(prices.InnerHtml);
label2.Visible = false;
label3.Visible = false;
}
Then I add the values into the database:
using (var con = new SqlConnection(connectionString))
{
con.Open();
using (var cmd = new SqlCommand(#"INSERT INTO OnlineProductsTemp$(CompetitorID, ProductCode, ProductName, DateCaptured)
VALUES(#CompetitorID, #ProductCode, #ProductName, #DateCaptured)", con))
{
cmd.Parameters.Add("#CompetitorID", SqlDbType.Int);
cmd.Parameters.Add("#ProductCode", SqlDbType.VarChar);
cmd.Parameters.Add("#ProductName", SqlDbType.VarChar);
cmd.Parameters.Add("#Price", SqlDbType.Decimal);
cmd.Parameters.Add("#DateCaptured", SqlDbType.DateTime);
for (int i = 0; i < competitorList.Count; i++)
{
cmd.Parameters["#CompetitorID"].Value = competitorList[i];
cmd.Parameters["#ProductCode"].Value = productCodeList[i];
cmd.Parameters["#ProductName"].Value = productNameList[i];
cmd.Parameters["#Price"].Value = productPriceList[i];
cmd.Parameters["#DateCaptured"].Value = dateCapturedList[i];
int rowsAffected = cmd.ExecuteNonQuery();
}
Everything works correctly but I cant seem to find a way to correctly convert InnerHtml values to a Decimal type. Is there a way of achieving this?
Depending on your values that come from inner html you can do something like this
using (var con = new SqlConnection(connectionString))
{
con.Open();
using (var cmd = new SqlCommand(#"INSERT INTO OnlineProductsTemp$(CompetitorID, ProductCode, ProductName, DateCaptured)
VALUES(#CompetitorID, #ProductCode, #ProductName, #DateCaptured)", con))
{
cmd.Parameters.Add("#CompetitorID", SqlDbType.Int);
cmd.Parameters.Add("#ProductCode", SqlDbType.VarChar);
cmd.Parameters.Add("#ProductName", SqlDbType.VarChar);
cmd.Parameters.Add("#Price", SqlDbType.Decimal);
cmd.Parameters.Add("#DateCaptured", SqlDbType.DateTime);
for (int i = 0; i < competitorList.Count; i++)
{
cmd.Parameters["#CompetitorID"].Value = competitorList[i];
cmd.Parameters["#ProductCode"].Value = productCodeList[i];
cmd.Parameters["#ProductName"].Value = productNameList[i];
cmd.Parameters["#Price"].Value = productPriceList[i];
cmd.Parameters["#DateCaptured"].Value = dateCapturedList[i];
int rowsAffected = cmd.ExecuteNonQuery(); // also the variable rowsAffected is not visible outside the scope of the for loop
}
}
}
Update:
You should, then, convert the values prior to adding them in the list, like so:
foreach (var prices in priceTags)
{
label9.Visible = true;
label9.Text += prices.InnerHtml + "\n";
productPriceList.Add(Decimal.Parse(prices.InnerHtml, <cultureInfoHere>));
label2.Visible = false;
label3.Visible = false;
}
By doing this you don't have to change the list type.

Categories