LIKE expression does not work a query in C# - c#

I want to search the records that have 3 or more '#'.
In MSAccess I can Write this and show me the results:
SELECT * FROM AlmLotes WHERE Lote LIKE '[#][#][#]*';
But in C# don't works.
DataTable dtResultats = new DataTable();
string strConnectionSource = MYCONNECTIONSTRING
OleDbConnection connAccess = new OleDbConnection(strConnectionSource);
connAccess.Open();
string strSQL = "SELECT * FROM AlmLotes WHERE Lote LIKE '[#][#][#]*'";
OleDbCommand cmd = new OleDbCommand(strSQL, connAccess);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd);
dtResultats = new DataTable();
try
{
myDataAdapter.Fill(dtResultats);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
for (int i = 0; i < dtResultats.Rows.Count; i++)
{
var rows = dtResultats.Rows[i];
for (int z = 0; z < dtResultats.Columns.Count; z++)
{
Console.WriteLine(dtResultats.Columns[z].ColumnName + ": " + rows[z] + Environment.NewLine);
}
}
Console.ReadKey();
The SQL Query in MSAcces show me 5 results.
THE SQL QUery in C# show me 0 results.

Try this:
string strSQL = #"SELECT * FROM AlmLotes WHERE Lote LIKE LIKE '[[#]%'";

So Ms Access use *, but C# OleDb use %. You can replace * to %.
string strSQL = #"SELECT * FROM AlmLotes WHERE Lote LIKE '###%'";

The solution are the Parameters:
string strSQL = "SELECT * FROM AlmLotes WHERE Lote LIKE #PARAM1";
OleDbCommand cmd = new OleDbCommand(strSQL, connAccess);
OleDbParameter param = cmd.CreateParameter();
param.DbType = DbType.String;
param.Direction = ParameterDirection.Input;
param.OleDbType = OleDbType.VarChar;
param.ParameterName = "PARAM1";
param.Value = "###%";
cmd.Parameters.Add(param);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd);
dtResultats = new DataTable();

Related

How to search between 2 dates on access database vs?

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

Select SQL using c# error can someone guide this one

What I'm missing?
I've got error:
Sqlexception was unhandled by usercode
SqlConnection con = new SqlConnection(MyConnectionString);
SqlCommand objCmd;
con.Open();
SqlDataReader dtReader;
String strSQL;
strSQL = "SELECT * FROM " + DropDownList1.SelectedValue + "'";
objCmd = new SqlCommand(strSQL, con);
dtReader = objCmd.ExecuteReader();
//*** BindData to GridView ***//
GridView3.DataSource = dtReader;
GridView3.DataBind();
dtReader.Close();
dtReader = null;
Try this ,
strSQL = "SELECT * FROM " + DropDownList1.SelectedValue;
ie., just remove ' from the query string.
Then add the following code at the end.
GridView3.DataSource = dtReader;
GridView3.DataSourceID = String.Empty;
GridView3.DataBind();
this code works now
SqlConnection con = new SqlConnection(MyConnectionString);
SqlCommand objCmd;
con.Open();
SqlDataReader dtReader;
String strSQL;
strSQL = "SELECT * FROM " + DropDownList1.SelectedValue ;
objCmd = new SqlCommand(strSQL, con);
dtReader = objCmd.ExecuteReader();
GridView3.DataSource = dtReader;
GridView3.DataSourceID = String.Empty;
GridView3.DataBind();
dtReader.Close();
dtReader = null;

How to count the number of rows from sql table in c#?

How to count the number of rows from sql table in c#?
I need to extract some data from my database...
You may try like this:
select count(*) from tablename where columname = 'values'
C# code will be something like this:-
public int A()
{
string stmt = "SELECT COUNT(*) FROM dbo.tablename";
int count = 0;
using(SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
{
using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
You need to make a database connection from c# first. Then, you need to pass below query as commandText.
Select count(*) from TableName
Use ExecuteScalar/ExecuteReader to get the returned count.
Do you means likes this ?
SELECT COUNT(*)
FROM yourTable
WHERE ....
You can make global function that you can use all the time as
public static int GetTableCount(string tablename, string connStr = null)
{
string stmt = string.Format("SELECT COUNT(*) FROM {0}", tablename);
if (String.IsNullOrEmpty(connStr))
connStr = ConnectionString;
int count = 0;
try
{
using (SqlConnection thisConnection = new SqlConnection(connStr))
{
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
catch (Exception ex)
{
VDBLogger.LogError(ex);
return 0;
}
}
This works for me
using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}
For more information consult: https://learn.microsoft.com/es-es/ef/ef6/querying/raw-sql?redirectedfrom=MSDN
Use this its working
string strQuery = "SELECT * FROM staff WHERE usertype='lacturer'";
connect.Open();
SqlCommand cmd = new SqlCommand(strQuery, connect);
SqlDataAdapter OleDbDa = new SqlDataAdapter(cmd);
DataSet dsData = new DataSet();
OleDbDa.Fill(dsData);
connect.Close();
std.Text = dsData.Tables[0].Rows.Count.ToString();
I used this method in my own application to count the number of active users within the program. This can be easily manipulated for your own use.
con.open();
string ActiveUsers = "SELECT * FROM Devices WHERE Status='" + "Online" + "'";
SqlCommand cmd = new SqlCommand(ActiveUsers, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
con.Close();
Users.Text = ds.Tables[0].Rows.Count.ToString();

C# How can i update some column datetime in datagridview to database

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.

SqlCeDataReader parameter ordinal = 1

I a Parameter ordial = 1 error on this code.
Can anyone explain it in this context? dbCon is correct as I can insert data to the database just trying out how to get it back no.
if (dbCon.State == ConnectionState.Closed)
{
dbCon.Open(); ;
}
SqlCeParameter vetidfromdropbox = new SqlCeParameter("#vetidfromdropbox", SqlDbType.Int);
vetidfromdropbox.Value = 2;
SqlCeCommand mySQLCommand = new SqlCeCommand("SELECT * FROM vets WHERE vetID = #vetidfromdropbox", dbCon);
SqlCeDataReader rdata = mySQLCommand.ExecuteReader();
if(rdata.Read()){
editNameTextbox.Text = (String)rdata["vetName"];
editSurnameTextbox.Text = (String)rdata["vetSurname"];
editCompanyNameTextbox.Text = (String)rdata["vetCompanyName"];
editPractiseAddTextBox.Text = (String)rdata["vetPractiseAddress"];
editMobileTextbox.Text = (String)rdata["vetMobile"];
editOtherTextbox.Text = (String)rdata["vetOther"];
editNotesTextbox.Text = (String)rdata["vetNotes"];
}else{
MessageBox.Show(" There has been an error with Read() ");
}
if (dbCon.State == ConnectionState.Open)
{
dbCon.Close();
}
You didn't add parameter to your SQL command:
var vetidfromdropbox = new SqlCeParameter("#vetidfromdropbox", SqlDbType.Int);
vetidfromdropbox.Value = 2;
var mySQLCommand = new SqlCeCommand(
"SELECT * FROM vets WHERE vetID = #vetidfromdropbox", dbCon);
mySQLCommand.Parameters.Add(vetidfromdropbox);
You can use AddWithValue to simplify the syntax:
var mySQLCommand = new SqlCommand(
"SELECT * FROM vets WHERE vetID = #vetidfromdropbox", dbCon);
mySQLCommand.Parameters.AddWithValue("vetidfromdropbox", 2);
Side note: use using on your sql connection and command to guarantee disposal and to simplify code.

Categories

Resources