I'm using c# and this error is becoming headache for me. I do not know how to solve this error .
can anyone help me to solve this. Here is the code
try
{
string MyConnection2 = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\DELL\Documents\db1.mdb";
//Display query
string Query = "select riq_num , department, item_name , item_unit , no_of_stock_out , itemtype from outputdet1 where riq_num = " + textBox2.Text + " or department= '" + comboBox1.Text + " ' or item_name= '" + textBox4.Text + "' or item_unit= '" + comboBox2.Text + "' or no_of_stock_out = " + textBox6.Text + " or itemtype = '" + comboBox3.Text + "' ; ";
OleDbConnection MyConn2 = new OleDbConnection(MyConnection2);
OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
MyConn2.Open();
//For offline connection we will use MySqlDataAdapter class.
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
// here i have assign dTable object to the dataGridView1 object to display data.
dataGridView1.DataSource = dTable;
MyConn2.Close();
}
// OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2);
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I assumed that textBox2.Text & textBox6.Text return a string from textbox control, so that OleDbCommand will throwing exception when it contains empty value or any non-numeric string since it will form invalid SQL statement. Use parameterized query like this example:
string Query = #"select riq_num, department, item_name, item_unit, no_of_stock_out, itemtype
from outputdet1
where riq_num = #riq_num
or department= #department
or item_name= #item_name
or item_unit= #item_unit
or no_of_stock_out = #no_of_stock_out
or itemtype = #itemtype";
using (OleDbConnection MyConn2 = new OleDbConnection(MyConnection2))
{
using (OleDbCommand MyCommand2 = new OleDbCommand(Query, MyConn2))
{
MyConn2.Open();
MyCommand2.Parameters.Add("#riq_num", textBox2.Text);
MyCommand2.Parameters.Add("#department", comboBox1.Text);
MyCommand2.Parameters.Add("#item_name", textBox4.Text);
MyCommand2.Parameters.Add("#item_unit", comboBox2.Text);
MyCommand2.Parameters.Add("#no_of_stock_out", textBox6.Text);
MyCommand2.Parameters.Add("#itemtype", comboBox3.Text);
// execute the query here
}
}
Remember that using statements used to dispose OLEDB connection immediately after it has closed so that GC can free up resources.
Additional note:
OleDbParameter works with parameter order instead of named parameters, hence ensure that the parameters are declared in their proper order from first to last.
Related
so I have this program which when I press a button inserts a record into an excel spreadsheet with, the columns, being , customer, product, weight, dateTime. Now I want to be able to update a record if the same customer, and product occurs, but I also want to add the previous weight field with the new field, and update the time.
The problem is i'm not sure how to modify my update statement to do this.
// Load data from database, and Update database if filed already exists
DataSet ds = new DataSet();
string insertquery = "SELECT * FROM [Sheet1$] where [Customer] = '" + lblcustomername + " ' ";
OleDbConnection myConnection = new OleDbConnection(OutputDatabaseConnectionString); //define new connection object
OleDbDataAdapter mydataadapter = new OleDbDataAdapter(insertquery, myConnection); //define data adaptor and select column data from spreadsheet
mydataadapter.Fill(ds);
int i = ds.Tables[0].Rows.Count;
// If item exists in database, update it
if (i > 0)
{
try
{
System.Data.OleDb.OleDbConnection myConnection2; //create new connection object
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
String sql = null;
myConnection2 = new System.Data.OleDb.OleDbConnection(OutputDatabaseConnectionString); //define connection string
myConnection2.Open();
myCommand.Connection = myConnection2;
sql = "UPDATE [Sheet1$] SET [Net Weight(Kg)]= '" + textBox1.Text + "' WHERE [Customer] = '" + lblcustomername + "'";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
myConnection2.Close();
myConnection2.Close(); //close connection
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// if it doesn't exist update database
try
{
System.Data.OleDb.OleDbConnection myConnection1; //create new connection object
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
String sql = null;
myConnection1 = new System.Data.OleDb.OleDbConnection(OutputDatabaseConnectionString); //define connection string
myConnection1.Open();
myCommand.Connection = myConnection1;
sql = sql = "INSERT INTO [Sheet1$] ([Customer],[Product],[Net Weight(Kg)], [DateTime]) VALUES('" + lblcustomername.Text + "','" + lblproductname.Text + "','" + textBox1.Text + "','" + (DateTime.Now).ToString() + "')";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
myConnection1.Close();
myConnection1.Close(); //close connection
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Mabuhay!
What is the most efficient or more convenient way to do this.
I have a select query and put it on a datagridview base on my filter. It has 5 columns. I want to know if Column CA from that Datagridview already exist on Table 2 which is on Column 3?
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=db;User ID=sa;Password=pw");
// DateTime dt = new DateTime();
//dt = DateTime.Now.ToString();
SqlDataAdapter sda = new SqlDataAdapter("SELECT max(PurchaseOrder.POTitle) as Description,sum(PurchaseOrderEntry.Price *PurchaseOrderEntry.QuantityOrdered) as Amount, max(PurchaseOrder.PONumber)as PONumber, " +
" max(PurchaseOrderEntry.OrderNumber) as BoxCount, max(PurchaseOrderEntry.OrderNumber) as PLC,max(PurchaseOrderEntry.OrderNumber) as Branch, max(PurchaseOrderEntry.OrderNumber) as PreparedBy, max(PurchaseOrderEntry.OrderNumber) as CheckedBy " +
" FROM PurchaseOrder LEFT OUTER JOIN" +
" PurchaseOrderEntry ON PurchaseOrder.ID = PurchaseOrderEntry.PurchaseOrderID" +
" WHERE (PurchaseOrder.Remarks like '%" + tanggapan.Text + "%') AND (PurchaseOrder.DateCreated BETWEEN '" + dateTimePicker1.Text + "' AND '" + dateTimePicker2.Text + "' and PurchaseOrder.OtherStoreID = '" + branch.Text + "') Group By PurchaseOrder.PONumber", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
This show my query filter. Any tip on how to do if PurchaseOrderEntry.OrderNumber already exist on my records so I can manage which one repeats.
Thank you!
Chris
I added this code now on my works and it is working now.
DataTable dt = new DataTable();
dt.Clear();
dt.Reset();
con.Close();
adaptors1.SelectCommand = con.CreateCommand();
adaptors1.SelectCommand.CommandText = "Select TOP 1 [ponumber],[clref] from [ISSPandayan].[dbo].[" + branch.Text + "] where [ponumber] = '" + dr.Cells["ponumber"].Value + "' ORDER BY [clref] ASC";
adaptors1.Fill(dt);
// select query para malam kung existing ponumber
if (dt.Rows.Count == 1)
{
adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = dt.Rows[0][1].ToString();
}
else
{
adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = " ";
}
//adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = "";
//MessageBox.Show(Convert.ToString(dr.Cells["description"].Value));
con.Close();
con.Open();
adaptorss.InsertCommand.ExecuteNonQuery();
adaptorss.InsertCommand.Parameters.Clear();
This is my screen shot
Bellow Is My Code For Update Button Click Event!
{
try
{
con = new SqlConnection(cs.ConDB);
con.Open();
string cb = "Update tblFees set Salutation= '" + cmbSalutation.Text + "' , Name= '" + tbName.Text + "',Sex = '" + cmbSex.Text + "', Date ='" + Date.Text + "',Fees_Amount='" + cmbFeesAmount.Text + "',Fees_Status='" + radioButton1.Checked + "'";
cmd = new SqlCommand(cb);
cmd.Connection = con;
cmd.ExecuteReader();
con.Close();
MessageBox.Show("Successfully updated", "Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
btnUpdate.Enabled = false;
btnSave.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
try
{
con = new SqlConnection(cs.ConDB);
con.Open();
cmd = new SqlCommand("SELECT * From tblFees", con);
SqlDataAdapter myDA = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
myDA.Fill(myDataSet, "tblFees");
dataGridView1.DataSource = myDataSet.Tables["tblFees"].DefaultView;
con.Close();
}catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);}`
Please Solve my problem i am new in the programming world
any help would be greatly appreciated
you should specify the rows using where condition
For example you can modify your query something like the following. I assume cboUser is a combo box there you can select particular user, so that the data updated for that selected user only.
SqlConnection con = new SqlConnection();
con.Open();
string cb = "Update [tblFees] set Salutation=#Salutation, Name=#Name,Sex =#Sex where tblFeesPK=#pk'";
SqlCommand cmd = new SqlCommand(cb, con);
cmd.Parameters.AddWithValue("#Salutation", cmbSalutation.Text);
cmd.Parameters.AddWithValue("#Name", tbName.Text);
cmd.Parameters.AddWithValue("#Sex", cmbSex.Text);
cmd.Parameters.AddWithValue("#pk", cboUser.SelectedValue);
cmd.ExecuteNonQuery();
If you want to update details based on name means: you can give name
in where condition. but it's not a proper way. so use primary
key(since name may have duplicate values)
You need to change the statement as:
string cb = "Update tblFees set Salutation= '" + cmbSalutation.Text + "' , Name= '" + tbName.Text + "',Sex = '" + cmbSex.Text + "', Date ='" + Date.Text + "',Fees_Amount='" + cmbFeesAmount.Text + "',Fees_Status='" + radioButton1.Checked + "' where Name= '" + tbName.Text + "'";
You need to add where Name= '" + tbName.Text + "';
Now it will update those rows where Name matches
Also as un-lucky said u should use parameterized queries
I am very new to sqlite and c# and trying exporting a csv file to sqlite database using dataset.
but I get this error.
SQL logic error or missing database
no such column: P17JAW
code:
string strFileName = "I:/exploretest.csv";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(strFileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
DataTable tb = ds.Tables[0];
SQLiteConnection m_dbConnection;
m_dbConnection = new SQLiteConnection("Data Source= C:/Users/WebMobility.db; Version=3;");
m_dbConnection.Open();
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var Id = dr["Id"].ToString();
var VRM = dr["VehicleRegistration"].ToString();
var Points = Convert.ToInt32(dr["TicketScore"].ToString());
string sql = "insert into NaughtyList (Id,VRM,Points) values ( '" + Id + "'," + VRM + "," + Points + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();
}
CSV FILE CONTAINS
Id,VehicleRegistration,TicketScore
21,P17JAW,1
22,K1WOM,1
23,m4npr,4
25,G7EPS,4
Your problem is with the single quotes missing for VRM your query should be like:
string sql = #"insert into NaughtyList (Id,VRM,Points) values
( '" + Id + "','" + VRM + "'," + Points + ")";
//^^ ^^
From the values it appears that ID is of integer type, you can remove single quotes around ID.
You should parameterized your query that will save your from these errors. I am not sure if parameters are supported by SQLiteCommand if they are you can do something like:
string sql = #"insert into NaughtyList (Id,VRM,Points) values
(#Id,#VRM,#Points)";
and then
command.Parameters.AddWithValue("#id", Id);
command.Parameters.AddWithValue("#VRM", VRM);
command.Parameters.AddWithValue("#Points", Points);
I have to bind the datalist control as per the values inserted in the form of find frined.
here is my code:
protected void search_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mahi\Documents\Visual Studio 2010\Projects\fc 6-4\fc\App_Data\fc.mdf;Integrated Security=True;User Instance=True");
cn.Open();
string str = "select unm='" + funm_txt.Text + "' , university='" + DDLuni.SelectedItem + "', city='"+ DDLcity .SelectedItem +"' , yjoin='" + DDLyjoin.SelectedValue + "' ,yleave= '" + DDLycom.SelectedValue + "', ybatch='" + DDLbtch.SelectedValue + "' from profile";
SqlCommand cmd = new SqlCommand(str, cn);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(str, cn);
DataTable dt = new DataTable();
DataList1 .DataSource =dt;
DataList1.DataBind();
cn.Close();
}
There are few things I have noticed:
-First of all, you are highly vulnerable to sql-injection attacks as you are passing user entered values directly into the database. You can avoid this by using a parameterised query.
-Secondly, you need to filter the records in a WHERE clause. At the moment you are assigning user typed/selected values into a select query.
-And you need to use SelectedValue of dropdown list not SelectedItem
-Also you can use using() blocks to get SqlConnection and DataAdapter Disposed at the end.
Try this (Please replace col1, col2 as required and complete the query assigning all parameters):
DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection("your_conn_string"))
{
string str = "Select Col1, Col2,... From profile " +
"Where unm = #unm and university= #uni and " +
"..." +
"ybatch = #ybatch";
SqlCommand cmd = new SqlCommand(str, cnn);
cmd.Parameters.AddWithValue("#unm",funm_txt.Text);
cmd.Parameters.AddWithValue("#uni",DDLuni.SelectedValue);
...
cmd.Parameters.AddWithValue("#ybatch",DDLbtch.SelectedValue);
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = cmd;
cnn.Open();
adapter.Fill(dt);
}
}
DataList1.DataSource =dt;
DataList1.DataBind();
try this,
cn.Open();
string str = "select unm='" + funm_txt.Text + "' , university='" + DDLuni.SelectedItem + "', city='"+ DDLcity .SelectedItem +"' , yjoin='" + DDLyjoin.SelectedValue + "' ,yleave= '" + DDLycom.SelectedValue + "', ybatch='" + DDLbtch.SelectedValue + "' from profile";
SqlDataAdapter da = new SqlDataAdapter(str, cn);
DataTable dt = new DataTable();
da.fill(dt);
DataList1 .DataSource =dt;
DataList1.DataBind();
cn.Close();
Add following code:
Your SqlDataAdapter and SqlCommand is not communicating.
and you haven't filled Datatable with the result.
da.SelectCommand = cmd;
da.fill(dt);