inserted writes - c#

code :
SqlConnection sqlc = new SqlConnection(
"Data Source=" + Environment.MachineName + #"\SQLEXPRESS;" +
"Integrated security=true;" +
"database=someDB");
SqlCommand sqlcmd;
string tmp = string.Empty;
for(int i = 0; i < 100000; i++)
{
tmp += "inserto into [db].[Files](...) values (...);"
}
sqlcmd = new SqlCommand(tmp, sqlc);
try { sqlc.Open(); sqlcmd.ExecuteNonQuety(); } cathc{}
inserted only < 1000 writes
How write all 100000 writes ?? May be destroy and create sqlcmd?

You should probably split the commands up into smaller commands. Say, inserting 500 records per SqlCommand until you've inserted all your records.
int totalRecordsToWrite = 100000;
int maxRecordsPerCommand = 500;
SqlConnection sqlc = new SqlConnection(
"Data Source=" + Environment.MachineName + #"\SQLEXPRESS;" +
"Integrated security=true;" +
"database=someDB");
int currentRecord = 0;
while (currentRecord < totalRecordsToWrite)
{
SqlCommand sqlcmd;
string tmp = string.Empty;
for(int j = 0; j < maxRecordsPerCommand; j++)
{
currentRecord++;
if (currentRecord >= totalRecordsToWrite)
break;
// Insert record "currentRecord" of the 100000 here.
tmp += "inserto into [db].[Files](...) values (...);"
}
using (sqlcmd = new SqlCommand(tmp, sqlc))
{
try { sqlc.Open(); sqlcmd.ExecuteNonQuety(); } catch{}
}
}

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 handle Datarow DBNull

The following code return empty cells for the ones who are stored as text" Number Stored as Text" How can I get the value of these cells ?
string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=2';");
foreach (var sheetName in GetExcelSheetNames(connectionString))
{
using (OleDbConnection con1 = new OleDbConnection(connectionString))
{
var dt = new DataTable();
string query = string.Format("SELECT * FROM [{0}]", sheetName);
con1.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con1);
adapter.Fill(dt);
for (int i = 1; i < dt.Rows.Count; i++)
{
for (int j = 1; j < dt.Columns.Count; j ++)
{
MessageBox.Show(dt.Rows[0][j].GetType().ToString());
}
}
var cell = dt.Rows[0][j] == System.DBNull.Value ? "null...", dt.Rows[0][j];
Use IMEX=1 for mixed types in connection string.

How to invoke class method in asp.net [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
This is my code:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.Common;
public class General_function
{
internal System.Windows.Forms.DataGridView DG_ItemShow;
public static object Get_Single_Value(string SQLQuery)
{
try
{
object SingleValue = null;
DbConnection cn = database_Object.GetConnection(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
if (cn.State == ConnectionState.Closed)
{
cn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cn.Open();
}
cmd.Connection = cn;
cmd.CommandText = SQLQuery;
SingleValue = cmd.ExecuteScalar;
return SingleValue;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Get_Single_Value : " + ex.Message);
}
}
public static long get_Max_value(string tablename, string fieldname)
{
try
{
long maxvalue = 0;
DbConnection cn = database_Object.GetConnection(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
if (cn.State == ConnectionState.Closed)
{
cn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cn.Open();
}
cmd.Connection = cn;
cmd.CommandText = "select max(" + fieldname + ") From " + tablename;
string res = null;
res = cmd.ExecuteScalar.ToString;
if (string.IsNullOrEmpty(res))
{
maxvalue = 0;
}
else
{
maxvalue = long.Parse(res);
}
return maxvalue;
}
catch (Exception ex)
{
Interaction.MsgBox("Error in get_Max_value" + ex.Message);
}
}
public static int Save_Record(ArrayList Al, string TableName)
{
try
{
int Retval = 0;
Trasns_DataDataSet ds = new Trasns_DataDataSet();
DataTable dt = ds.Tables(TableName);
ArrayList tal = new ArrayList();
foreach (DataColumn cl in dt.Columns)
{
tal.Add(cl.ColumnName);
}
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string n = null;
for (int i = 0; i <= tal.Count - 1; i++)
{
n = "#" + tal(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = n;
pa.Value = Al(i);
cmd1.Parameters.Add(pa);
}
n = "";
string v = "";
string sqlstr = "insert into " + TableName + " (";
for (int i = 0; i <= tal.Count - 1; i++)
{
n = n + "," + tal(i).ToString;
v = v + ",#" + tal(i).ToString;
}
n = Strings.Right(n, Strings.Len(n) - 1);
v = Strings.Right(v, Strings.Len(v) - 1);
sqlstr = sqlstr + n + ") values (" + v + ")";
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Save_Record : " + ex.Message);
}
}
public static int Delete_Record(ArrayList AlName, ArrayList AlValue, string TableName)
{
try
{
int Retval = 0;
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string m = null;
for (int i = 0; i <= AlName.Count - 1; i++)
{
m = "#" + AlName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlValue(i);
cmd1.Parameters.Add(pa);
}
string sqlstr = "delete from " + TableName + " where ";
string v = "";
for (int i = 0; i <= AlName.Count - 1; i++)
{
v = v + " And " + AlName(i).ToString + "=#" + AlName(i).ToString;
}
v = Strings.Right(v, Strings.Len(v) - 4);
sqlstr = sqlstr + v;
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Delete_Record : " + ex.Message);
}
}
public static int Modify_Record(ArrayList AlName, ArrayList AlValue, ArrayList
AlPKName, ArrayList AlPKValue, string TableName)
{
try
{
int Retval = 0;
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string m = null;
//values parameters
for (int i = 0; i <= AlName.Count - 1; i++)
{
m = "#" + AlName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlValue(i);
cmd1.Parameters.Add(pa);
}
//primary key column parameters
for (int i = 0; i <= AlPKName.Count - 1; i++)
{
m = "#" + AlPKName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlPKValue(i);
cmd1.Parameters.Add(pa);
}
string sqlstr = "update " + TableName + " set ";
string v = "";
for (int i = 0; i <= AlName.Count - 1; i++)
{
v = v + "," + AlName(i).ToString + "=#" + AlName(i).ToString;
}
string w = "";
for (int i = 0; i <= AlPKName.Count - 1; i++)
{
w = w + " And " + AlPKName(i).ToString + "=#" + AlPKName(i).ToString;
}
v = Strings.Right(v, Strings.Len(v) - 1);
w = Strings.Right(w, Strings.Len(w) - 4);
sqlstr = sqlstr + v + " Where " + w;
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Modify_Record : " + ex.Message);
}
}
public static DataTable RecordSearch(string SqlString, string TableName)
{
try
{
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
Trasns_DataDataSet ds = new Trasns_DataDataSet();
DataTable dt = default(DataTable);
DbDataAdapter da = database_Object.GetAdapter(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
cmd.Connection = cnn;
cmd.CommandText = SqlString;
da.SelectCommand = cmd;
da.Fill(ds, TableName);
dt = ds.Tables(TableName);
cnn.Close();
cmd.Dispose();
da.Dispose();
cnn.Dispose();
return dt;
}
catch (Exception ex)
{
Interaction.MsgBox("error in RecordSearch : " + ex.Message);
}
}
}
How can I call the this class method from another page?
Using your static methods, you just call them by referencing the namespace:
object result = General_function.Get_Single_Value("select * from table");
as shown in code, you defined method as static so in order to invoke that method u can use,
var o = General_function.Get_Single_Value("your_parameter");
and
long lobj = General_function.get_Max_value("table_name","field_name");
and so on...

updating column value in Ms-Access 2010 using c# and oledb query

I am struggling for updating record/columnvalue in MS-ACCESS database... help would be appreciated a lot..!
I am displaying a list of partnumbers retrieved from a table in Ms-access using Datagridview in which I am supposed to update/change partnumber. ( 'partno' is 3rd column of my datagridview.)
But I am unable to Update a single record in database..no exceptions.. everything is going fine.!
But no rows are effected!
Here is my code:
private void UpdateDetails_Click(object sender, EventArgs e)
{
try
{
con = new OleDbConnection();
con.ConnectionString = Helper.MyConnectionString;
con.Open();
for (int i = 0; i <= datagridview1.Rows.Count-1; i++)
{
int j = i + 1; // j is the serial number corresponding to partnumber
string partno = dgv1.Rows[i].Cells[2].Value.ToString(); //getting part number from Datagridview
String partquery = "";
if (partno == null || partno == "") //checking whether part number updated or not
{
partquery = "update Vendor SET PartNo=NULL where Vendor.Sno=" + j + " ";
}
else
partquery = "update Vendor SET PartNo='" + partno + "' where Vendor.Sno=" + j + " ";
//Vendor is the table name containg 'partno' list
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = partquery;
cmd.ExecuteNonQuery();
}
}
catch(Exception ex)
{
//exception handler
}
}
As #Soner suggested you should use parameters. Something like this.
Modified the code did you do something like this?
private void UpdateDetails_Click(object sender, EventArgs e)
{
try
{
con = new OleDbConnection();
con.ConnectionString = Helper.MyConnectionString;
con.Open();
for (int i = 0; i <= datagridview1.Rows.Count - 1; i++)
{
int j = i + 1; // j is the serial number corresponding to partnumber
string partno = dgv1.Rows[i].Cells[2].Value.ToString(); //getting part number from Datagridview
//String partquery = "";
//if (partno == null || partno == "") //checking whether part number updated or not
//{
// partquery = "update Vendor SET PartNo=NULL where Vendor.Sno=" + j + " ";
//}
//else
// partquery = "update Vendor SET PartNo='" + partno + "' where Vendor.Sno=" + j + " ";
OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("update Vendor SET PartNo='#partno' where Vendor.Sno=#vndid");
OleDbParameter parameter = new System.Data.OleDb.OleDbParameter("#partno", partno);
cmd.Parameters.Add(parameter);
parameter = new System.Data.OleDb.OleDbParameter("#vndid", j);
cmd.Parameters.Add(parameter);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//exception handler
}
}

Categories