data reader is not reading the data from the table - sql-server

I am using the data reader to show specific column data into grid view. Actually i want to get the last day record from table.
DateTime yestarday = DateTime.Today.AddDays(-1);
string query = "select NAME,CLOSING_READING,RATE from CASHSALE_DETAIL where DATE = '" + yestarday + "'";
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandText = query;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
CashSaleVoucherGridView.Rows.Add(num, "", dr["NAME"].ToString(), dr["CLOSING_READING"].ToString(), "", "", "", dr["RATE"].ToString());
num++;
}
On above given query data reader returns me 0 record.
Any Suggstions????

First check if your select query it its returning records then
add dr.HasRows to check your data reader return rows or not
DateTime yesterday = DateTime.Today.AddDays(-1);
string query = "select NAME,CLOSING_READING,RATE from CASHSALE_DETAIL where DATE = #date";
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#date", yesterday );
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
CashSaleVoucherGridView.Rows.Add(num, "", dr["NAME"].ToString(), dr["CLOSING_READING"].ToString(), "", "", "", dr["RATE"].ToString());
num++;
}
}
else
{
//Throw error ("No rows found.");
}
Best Regards

the issue is on this statement
string query = "select NAME,CLOSING_READING,RATE from CASHSALE_DETAIL where DATE = '" + yestarday + "'";
use parameterized command
DateTime yesterday = DateTime.Today.AddDays(-1);
string query = "select NAME,CLOSING_READING,RATE from CASHSALE_DETAIL where DATEADD(dd, 0, DATEDIFF(dd, 0, DATE )) = DATEADD(dd, 0, DATEDIFF(dd, 0, #yesterday))";
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#yesterday", yesterday);
SqlDataReader dr = cmd.ExecuteReader();

You can format the date field like this
string query = "select NAME,CLOSING_READING,RATE from CASHSALE_DETAIL
where convert(varchar(15),DATE,101)= '" + yestarday + "'";
but the method mentioned by #BizApps and #mdcuesta like below is very less erroneous
cmd.Parameters.AddWithValue("#yesterday", yesterday);

Related

ado.net does not return data in SQL Builtin function

I have following method, but it does not fill datatable.
using (conn = new SqlConnection(Connection1))
{
conn.Open();
string query = "SELECT distinct left(RTRIM(PostalCode), 2),EntityID FROM Gen_Addresses";
dt = new DataTable();
ad = new SqlDataAdapter(query ,conn);
ad.Fill(dt);
checkedListBox1.DisplayMember = dt.Columns["PostalCode"].ColumnName;
checkedListBox1.ValueMember = dt.Columns["EntityID"].ColumnName;
}
using (conn = new SqlConnection(Connection1))
{
conn.Open();
string query = "SELECT distinct left(RTRIM(PostalCode), 2),EntityID FROM Gen_Addresses";
SqlCommand cmd=null;
cmd=new SqlCommand(query ,conn);
dt = new DataTable();
ad = new SqlDataAdapter();
ad.SelectCommand=cmd;
ad.Fill(dt);
checkedListBox1.DisplayMember = dt.Columns["PostalCode"].ColumnName;
checkedListBox1.ValueMember = dt.Columns["EntityID"].ColumnName;
}
try this
You need to specify a column alias in the query in order to reference the expression by name instead of ordinal:
string query = "SELECT distinct left(RTRIM(PostalCode), 2) AS PostalCode,EntityID FROM Gen_Addresses";

I am getting an execption as object reference not set to an instance of an object. Code is as follows :

public void showdata(string pss, string cipherText)
{
SqlConnection conn1 = new SqlConnection(str);
SqlCommand cmd1 = new SqlCommand("update Tbl_Users set Password = '" + pss + "'where Password ='" + cipherText + "'", conn1);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
sda1.Fill(ds1, "Tbl_Users");
dataGridView1.DataSource = ds1;
dataGridView1.DataMember = ds1.Tables["Tbl_Users"].ToString();
}
Ur Updated Ans
public void showdata(string pss, string cipherText)
{
SqlConnection conn1 = new SqlConnection(str);
> SqlCommand cmd1 = new SqlCommand("**update Tbl_Users set Password = '" +
> pss + "'where Password ='" + cipherText + "'"**, conn1);
It should be select statment not Update Or Inser Statment
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
Datatable ds1 = new Datatable ();
sda1.Fill(ds1);
dataGridView1.DataSource = ds1;
}

Insert with parameters

I should change all queries to use parameters to protect app from SQL injection.
Current insert sample which works is:
If Len(ExecuteQuery("INSERT INTO ICE_Order_Details(Order_ID, Product_ID, License_Type_ID, Maintenance_ID, Qty, Shareit_Running_No, Price, Total) VALUES(" & OrderID & ", " & ProductID & ", " & LicenseTypeID & ", " & MaintenanceID & ", " & Val(Request("QUANTITY")) & ", " & Val(Request("RUNNING_NO")) & ", " & Price & ", " & Price * Val(Request("QUANTITY")) & ")")) > 0 Then
'SendBadRequest "Could not run insert Order detail query"
Can you help me to write parametric query instead of this?
I tried a lot of ways to do this but here is below last one.
Dim ConnString As New SqlConnection("Provider=SQLOLEDB.0;Data Source=something;Initial Catalog=something;Persist Security Info=True;User ID=something;Password=something")
Dim SqlString As String ="INSERT INTO ICE_Order_Details(Order_ID, Product_ID, License_Type_ID, Maintenance_ID, Qty, Shareit_Running_No, Price, Total) VALUES(#OrderID, #ProductID, #LicenseTypeID, #MaintenanceID, #Qty, #RunningNo, #Price, #Total)"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#OrderID", OrderID)
cmd.Parameters.AddWithValue("#ProductID", ProductID)
cmd.Parameters.AddWithValue("#LicenseTypeID", LicenseTypeID)
cmd.Parameters.AddWithValue("#MaintenanceID", MaintenanceID)
cmd.Parameters.AddWithValue("#Qty", Val(Request("QUANTITY")))
cmd.Parameters.AddWithValue("#RunningNo", Val(Request("RUNNING_NO")))
cmd.Parameters.AddWithValue("#Price", Price)
cmd.Parameters.AddWithValue("#Total", Price * Val(Request("QUANTITY")))
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Edit: It still doesn't work. Here is my current code for adding parameters:
cmd.Parameters.Add("#OrderID", SqlDbType.Int).Value = OrderId
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = ProductID
cmd.Parameters.Add("#LicenseTypeID", SqlDbType.Int).Value = LicenseTypeID
cmd.Parameters.Add("#MaintenanceID", SqlDbType.Int).Value = MaintenanceID
cmd.Parameters.Add("#Qty", SqlDbType.Int).Value = Int32.Parse(Request("QUANTITY"))
cmd.Parameters.Add("#RunningNo", SqlDbType.Int).Value = Int32.Parse(Request("RUNNING_NO"))
cmd.Parameters.Add("#Price", SqlDbType.Money).Value = Money.Parse(Price)
cmd.Parameters.Add("#Total", SqlDbType.Money).Value = Money.Parse(Price * Int32.Parse(Request("QUANTITY")))
Edit: I changed my insert query to test only insert with parameters. But it don't work
Dim ConnString As String = ConfigurationManager.ConnectionStrings("DB_Connection_String0").ConnectionString
Dim SqlString As String ="INSERT INTO Unsubscribed(E-Mail) VALUES(#E-Mail)"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#E-Mail", SqlDbType.nvarchar).Value = "testiram#obrisime.sada"
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
here is error which i got (it marked 'As') if I change connection string it show error on next 'As' in code with same error message
Microsoft VBScript compilation error '800a0401'
Expected end of statement
/Test.asp, line 8
Dim ConnString As String =
ConfigurationManager.ConnectionStrings("DB_Connection_String0").ConnectionString
---------------^
Finally I found solution for this
Thanks all for help!
here is code below which work fine
<%
Dim oConn, oCmd, ds, sql
p1 = "test"
p2 = "test"
p3 = "test"
ds = "Provider=SQLOLEDB.1;Data Source=___;Initial Catalog=___;User ID=___;Password=___;"
sql = "INSERT INTO table (prop1, prop2, prop3) VALUES (?,?,?)"
Set oConn=Server.CreateObject("ADODB.Connection")
oConn.Open ds
Set oCmd = Server.CreateObject("ADODB.Command")
oCmd.ActiveConnection = oConn
oCmd.CommandText = sql
oCmd.CommandType = 1
oCmd.Parameters(0) = p1
oCmd.Parameters(1) = p2
oCmd.Parameters(2) = p3
oCmd.Execute()
oConn.close
Set oConn=nothing
%>
it is better to use sqlhelper class file by microsoft which i think is best for this cause and is relatively easy to use and shortens code by much. e.g
in save click event it will go like this
sqlParameter[] parem=
{
new sqlparameter("#value1"urcontrol.text),
new sqlparameter("#value2"urcontrol.text),
new sqlparameter("#value3"urcontrol.text)
};
sqlhelper.executenonquery (connectionstring,commandtype.storeprocedure,"ProcedureName",parem);
rest will be handled automatically by sqlhelper class file

Controlling Excel through VB.NET [duplicate]

myConnection.Open()
rtb_Address.Clear()
txt_Name.Clear()
Dim str As String
str = "SELECT * FROM table1 WHERE (cus_ID = '" & txt_ID.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader()
While dr.Read()
rtb_Address.Text = dr("cus_Addr").ToString
txt_Name.Text = dr("cus_Name").ToString
End While
myConnection.Close()
Error in dr = cmd.ExecuteReader()
dr is declared as OleDbDataReader
cus_ID is probaly a numeric data type, but you try to query it with a string: (cus_ID = 'thevalue').
Just remove the enclosing ': (cus_ID = thevalue)
or better, use a parameterized query to prevent sql-injection.
I would recommend the following:
Using cmd As New OleDbCommand("SELECT * FROM table1 WHERE cus_ID = #ID", con)
cmd.Parameters.AddWithValue("#ID", txt_ID.Text)
dr = cmd.ExecuteReader()
While dr.Read()
rtb_Address.Text = dr("cus_Addr").ToString
txt_Name.Text = dr("cus_Name").ToString
End While
End Using

There was an error parsing the query.when retrieving data from a .sdf-file

I am writing a program in C# using Visual Studio 2008 and gets an error when retrieving data from a .sdf file
There was an error parsing the query in SqlCeConnection
My code is
SqlCeConnection conn = new SqlCeConnection(connStr);
SqlCeCommand cmd = new SqlCeCommand();
DataSet ds = new DataSet();
SqlCeDataAdapter da;
try
{
conn.Open();
cmd = conn.CreateCommand();
if(mode == "update")
cmd.CommandText = "SELECT eq_id, description, bl_id, fl_id, rm_id, modelno, category, eq_std, comments FROM eq where (isModified = 1) SELECT * FROM eq_log";
else if(mode == "create")
cmd.CommandText = "SELECT eq_id, description, bl_id, fl_id, rm_id, modelno, category, eq_std, comments FROM eq where (isModified = 2) SELECT * FROM eq_log";
da = new SqlCeDataAdapter(cmd);
da.Fill(ds);
return ds;
}
catch (Exception db)
{
}
The error is:
There was an error parsing the query.[ Token line number = 2,Token line offset = 1,Token in error = SELECT ]
Exception Details: System.Data.SqlServerCe.SqlCeException: There was an error parsing the query.There was an error parsing the query. [ Token line number = 2,Token line offset = 1,Token in error = SELECT
You have 2 select statement in cmd.CommandText. You need to separate them by ;.
SqlCeConnection conn = new SqlCeConnection(connStr);
SqlCeCommand cmd = new SqlCeCommand();
DataSet ds = new DataSet();
SqlCeDataAdapter da;
try
{
conn.Open();
cmd = conn.CreateCommand();
if(mode == "update")
cmd.CommandText = "SELECT eq_id, description, bl_id, fl_id, rm_id, modelno, category, eq_std, comments FROM eq where (isModified = 1); SELECT * FROM eq_log";
else if(mode == "create")
cmd.CommandText = "SELECT eq_id, description, bl_id, fl_id, rm_id, modelno, category, eq_std, comments FROM eq where (isModified = 2); SELECT * FROM eq_log";
da = new SqlCeDataAdapter(cmd);
da.Fill(ds);
return ds;
}
catch (Exception db)
{
}
Tell me if this is working for you or not.
You can only have a single SELECT per command with SQL Server Compact, so you must return two DataSets/DataTables

Resources