I'm using OLEDB to query an excel file using date time picker but I keep getting a Data type mismatch in cireria expression error.
The format in excel for the date is "6/08/2012 10:00"
DateTime time = dateTimePicker1.Value;
MyCommand = new OleDbDataAdapter("select * from [CR$] where ([Req Start Date] >='" + time + "')", MyConnection);
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
bindingSource1 = new BindingSource();
bindingSource1.DataSource = DtSet;
bindingSource1.DataMember = DtSet.Tables[0].TableName;
dataGridView1.DataSource = bindingSource1;
MyConnection.Close();
You are passing time to the query as a string, so you could ToString() it to make it work:
MyCommand = new OleDbDataAdapter("select * from [CR$] where ([Req Start Date] >='" + time.ToString("%M/dd/yyyy HH:mm") + "')", MyConnection);
But you really should make it a parameter. Plus, it's safer that way.
using (OleDbConnection connection = new OleDbConnection(yourConnectionString))
{
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [CR$] where [Req Start Date] >= ?", connection);
adapter.SelectCommand.Parameters.Add("#p1", OleDbType.Date);
adapter.SelectCommand.Parameters["#p1"].Value = time;
try
{
connection.Open();
adapter.Fill(DtSet);
}
catch (Exception ex)
{
//handle error
}
}
Find out more: OleDbParameter Class
Create an OleDbCommand and pass the value in as a parameter. Then use the Command as a parameter for the OleDbAdapter constructor...
string queryString = "select * from [CR$] where ([Req Start Date] >= ?)";
OleDbCommand command = new OleDbCommand(queryString, connection);
command.Parameters.Add("#p1", OleDbType.DateTime).Value = time;
MyCommand = new OleDbDataAdapter(queryString, MyConnection);
Related
I'm trying this code but it shows an error on da.Fill(dt)
No value given for one or more required parameters.
Why does it show that error? I clearly check all names of databases and tables and fields, they all are correct and I'm using date/time field for datetime.
Can you help me with this?
string conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ahmed\OneDrive\Documents\shop.accdb";
OleDbConnection ccc = new OleDbConnection(conn);
ccc.Open();
string css = "SELECT * from tbl3 Where dateitem between '" + dateTimePicker1.Value.ToString() + "%' AND '" + dateTimePicker2.Value.ToString()+"%'";
OleDbCommand non = new OleDbCommand(css, ccc);
OleDbDataAdapter da = new OleDbDataAdapter(non);
DataTable dt = new DataTable();
da.Fill(dt);
count = Convert.ToInt32(dt.Rows.Count.ToString());
dataGridView1.DataSource = new BindingSource(dt, null);
As others have mentioned you should use the parameters instead of hard coding the values.
using (OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ahmed\OneDrive\Documents\shop.accdb"))
{
conn.Open();
// DbCommand also implements IDisposable
using (OleDbCommand cmd = conn.CreateCommand())
{
var param1 = new OleDbParameter("#DateTimePicker1", OleDbType.DBDate); //you may have to play with different types
param1.Value = dateTimePicker1.Value;
cmd.Parameters.Add(param1);
var param2 = new OleDbParameter("#DateTimePicker2", OleDbType.DBDate);
param2.Value = dateTimePicker2.Value;
cmd.Parameters.Add(param2);
cmd.CommandText = "SELECT * from tbl3 Where datetime >= #DateTimePicker1 and datetime <= #DateTimePicker2";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
count = Convert.ToInt32(dt.Rows.Count.ToString());
dataGridView1.DataSource = new BindingSource(dt, null);
}
}
Hi I'm trying to search filter a datagridview by using a combobox and textbox.
I have successfully done so but it only works properly when I search for the ID column. Other columns just crash display the following message:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'Name LIKE 'd%'' at line 1
The d letter in that error message is just the letter I was trying to filter the search with.
Could somebody please help me solve this issue?
My code is below
string myConnection = "datasource=localhost;port=3306;username=root;password=;";
MySqlConnection conDatabase = new MySqlConnection(myConnection);
try
{
if (comboBoxSrchPatient.Text == "ID")
{
MySqlCommand cmd = new MySqlCommand("select * from clinic_inventory_system.patient WHERE ID LIKE '" + txtSearchPatient.Text + "%'", conDatabase);
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
else if (comboBoxSrchPatient.Text == "FIRST NAME")
{
MySqlCommand cmd = new MySqlCommand("select * from clinic_inventory_system.patient WHERE First Name LIKE '" + txtSearchPatient.Text + "%'", conDatabase);
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
else if (comboBoxSrchPatient.Text == "LAST NAME")
{
MySqlCommand cmd = new MySqlCommand("select * from clinic_inventory_system.patient WHERE Last Name LIKE '" + txtSearchPatient.Text + "%'", conDatabase);
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
else if (comboBoxSrchPatient.Text == "AGE")
{
MySqlCommand cmd = new MySqlCommand("select * from clinic_inventory_system.patient WHERE Age LIKE '" + txtSearchPatient.Text + "%'", conDatabase);
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
else if (comboBoxSrchPatient.Text == "CONTACT NUMBER")
{
MySqlCommand cmd = new MySqlCommand("select * from clinic_inventory_system.patient WHERE Contact Number LIKE '" + txtSearchPatient.Text + "%'", conDatabase);
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Your field names contains spaces.
To use them in a query your need to enclose them between backticks (ALT+096)
MySqlCommand cmd = new MySqlCommand(#"select * from
clinic_inventory_system.patient WHERE `Last Name` LIKE ....";
Said that, consider, as soon as possible, to change your queries to use a parameterized query
using(MySqlCommand cmd = new MySqlCommand(#"select * from
clinic_inventory_system.patient
WHERE `First Name` LIKE #name", conDatabase);
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = txtSearchPatient.Text + "%";
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
dataPatientGridView.DataSource = dbdataset;
}
In this way your code is safer because it is no more possible to build an Sql Injection attack against your db and, if the First Name contains a single quote, you don't have a syntax error again
First of all, with First Name, Last Name and Contact Number, you need to escape the columns correctly.
Since you're using MariaDB, you should use backticks (`) to escape the column names.
Secondly, your Age query fails because you can't perform a LIKE on a numeric column. You should use = (equals).
Hope that helps.
Also, considering switching to prepared statements if you're using data the user has provided directly in your SQL. At the moment, you're open to SQL Injection.
you should listen to Huw Jones.
you dont want to get audited by a security firm and have sql injection problems. Parameterized your query is mySql supports it.
I'm trying to sort for today. I am giving match error while I am comparing.
OleDbConnection baglanti = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Dragonfly\\Documents\\Visual Studio 2013\\WebSites\\WebSite2\\App_Data\\calismagunluk.mdb");
OleDbDataReader oku;
OleDbCommand sorgu =new OleDbCommand();
DateTime bugun = DateTime.Now.Date;
sorgu.CommandText = "select * from calisan where kulID=" + sesionKulId +
" AND gun='" + bugun + "' ";
oku = sorgu.ExecuteReader();//I give error in here
if (oku.HasRows) {
Repeater1.DataSource = oku;
Repeater1.DataBind();
oku.Dispose();}
else{
Repeater1.Visible = false;
repeaterBos.Text = "Bugün Hiç Çalışma Yapmamışsınız...";
oku.Dispose();
}
I am getting this error: "Data type mismatch in criteria expression".
If I change the db column to Text, it is working. But I don't want it this way. How should I follow the way?
You can bypass the format problem and let the command work the format by itself by using parameters:
OleDbConnection baglanti = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Dragonfly\\Documents\\Visual Studio 2013\\WebSites\\WebSite2\\App_Data\\calismagunluk.mdb");
OleDbDataReader oku;
OleDbCommand sorgu =new OleDbCommand();
DateTime bugun = DateTime.Now.Date;
sorgu.CommandText = "select * from calisan where kulID=#ID AND gun=#date";
sorgu.Parameters.Add("#ID", OleDbType.Integer).Value = susionKulId;
sorgu.Parameters.Add("#date", OleDbType.DBTimeStamp).Value = bugun;
i need update some column in datagridview to database. but don't update to database.
step one: i select datetime from datetimepicker.
step two: show datetime on datagridview.
step tree: i need update/edit on datagridview to database.
Display on Datagridview.
EmpNo fName ChkDate ChkIn ChkOut
00001 Al 01/10/2012 08:02 17:04
00002 Bik 01/10/2012 07:43 18:35
i need update fields "ChkIn" to database.
Code
SqlConnection Conn;
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
StringBuilder sb = new StringBuilder();
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),'" + dgvShow.Rows[i].Cells[3].Value + "',102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = '" + dateTimePicker.Value.ToString("yyyy-MM-dd") + "' and [filesTA].EmpNo = '" + dgvShow.Rows[i].Cells[0].Value + "'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds;
da.Update(ds);
}
}
Error: Update unable to find TableMapping['Table'] or DataTable 'Table'.
I try other code:
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM [filesTA]", appConn);
adapter.UpdateCommand = new SqlCommand("UPDATE [WebSP].[dbo].[filesTA]"
+ "SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')"
+ "FROM [WebSP].[dbo].[filesTA]"
+ "WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo", Conn);
adapter.UpdateCommand.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn");
adapter.UpdateCommand.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate");
adapter.UpdateCommand.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo");
DataSet ds = new DataSet();
adapter.Fill(ds);
dgvShow.DataSource = ds;
adapter.Update(ds);
this code not save to database.
Thanks for your time. :D
Type Database:
ChkIn and ChkDate Type DateTime,EmpNo Type NUMERIC
I try
int i;
for (i = 1; i < dgvShow.Rows.Count; i++)
{
if (dgvShow.Rows.Count > 0)
{
using (Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA]" +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':')" +
"FROM [WebSP].[dbo].[filesTA]" +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.DateTime, 10, "ChkIn").Value = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value).ToString();
cmd.Parameters.Add("#cDate", SqlDbType.DateTime, 10, "ChkDate").Value = Convert.ToDateTime(dateTimePicker.Value.ToString()).ToString();
cmd.Parameters.Add("#eNo", SqlDbType.Decimal, 10, "EmpNo").Value = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value).ToString();
cmd.ExecuteNonQuery();
}
}
}
Error: Conversion failed when converting date and/or time from character string. T__T
You could try to get rid of the SqlDataAdapter using directly a SqlCommand
Using(Conn = new SqlConnection(appConn))
{
Conn.Open();
string sql = "UPDATE [WebSP].[dbo].[filesTA] " +
"SET [filesTA].ChkIn = replace(convert(nvarchar(10),#cIn,102),'.',':') " +
"FROM [WebSP].[dbo].[filesTA] " +
"WHERE [filesTA].ChkDate = #cDate and [filesTA].EmpNo = #eNo";
SqlCommand cmd = new SqlCommand(sql, Conn);
cmd.Parameters.Add("#cIn", SqlDbType.NVarChar, 10, "ChkIn").Value =
dgvShow.Rows[i].Cells[3].Value;
cmd.Parameters.Add("#cDate", SqlDbType.NVarChar, 10, "ChkDate").Value =
dateTimePicker.Value.ToString("yyyy-MM-dd") ;
cmd.Parameters.Add("#eNo", SqlDbType.NVarChar, 10, "EmpNo").Value =
dgvShow.Rows[i].Cells[0].Value ;
cmd.ExecuteNonQuery();
}
Of course, when using parameters, we need to set their values before running the command.
However I really don't understand well the code to update the ChkIn field. That field (according to the Parameter type) is a nvarchar, then why don't you try to format your #cIn value directly in code and avoid the use of Sql Server Replace and Convert functions? Also the 102 is a Date Style. It is used to format Date expressions as strings with the yy.mm.dddd pattern, but you have a string that contains only time info.
For example
After your last edit - changed to this
DateTime chkIN = Convert.ToDateTime(dgvShow.Rows[i].Cells[3].Value);
DateTime chkDate = Convert.ToDateTime(dateTimePicker.Value.ToString("yyyy-MM-dd"));
decimal empNo = Convert.ToDecimal(dgvShow.Rows[i].Cells[0].Value) ;
cmd.Parameters.Add("#cIn", SqlDbType.DateTime).Value = chkIN;
cmd.Parameters.Add("#cDate", SqlDbType.DateTime).Value = chkDate;
cmd.Parameters.Add("#eNo", SqlDbType.Decimal).Value = empNo;
Also the syntax used in query could be the source of other problems, but I need to see your connection string.
I am trying to display the data using parametrized query
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #" Data Source=servername; Database=master; Trusted_Connection=yes ";
xconn.Open();
SqlCommand ycmd = new SqlCommand ("select * from tablename where column1 = #name", xconn);
ycmd.Parameters.Add("#name", dropdownlist.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(s,xconn);
SqlCommandBuilder cmdbuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
catch(Exception ex)
{
label.Text = ex.Message + "\n" + ex.StackTrace;
}
How do I get it to work?
Try this:
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #" Data Source=servername; Database=master; Trusted_Connection=yes";
SqlCommand ycmd = new SqlCommand ("select * from tablename where column1 = #name", xconn);
ycmd.Parameters.Add("#name", dropdownlist.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(ycmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
catch(Exception ex)
{
label.Text = ex.Message + "\n" + ex.StackTrace;
}
You don't need to call SqlConnection.Open() when you are using the SqlDataAdapter.Fill() method. In that method it opens up the connection and disposes/closes it when complete. (this isn't the problem, just an FYI)
The way you created your SqlDataAdapter is the problem. You didn't create it with the SqlCommand as a constructor, just the command text. Because of that, you didn't pass in the parameter that was specified in the SqlCommand class.
Let me know if that works. And if that doesn't work, try manually running this query in SSMS to ensure that it actually returns a result set. Also, make sure that your ListControl.SelectedValue property contains something. Do this by debugging and analyze what is stored there.