Datareader Exception Thrown Database - DateTime - c#

In my Access database I have an AutditLog table which Looks like this
I simply want to access this table and display each bit of information when Created*(which is the date of the logs) is equal to today's date.
this is my code
private void ITemail()
{
string FinEmail;
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
dbConnector.Connect();
var sqlStr = " SELECT Created, [Action], ConnectionLoc, ConnectionSystem, Resource, [Text], RecordId, ToVal, ClientName"
+ "FROM tblAudit WHERE (ClientName = '" + Client + "') AND 'Created' = '" + ToDate() + "'";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
txtIT.Text = dr[0].ToString() + dr[1].ToString() + dr[2].ToString() + dr[3].ToString() + dr[4].ToString() + dr[5].ToString() + dr[6].ToString()
+ dr[7].ToString() + dr[8].ToString();
}
}
private string ToDate()
{
return DateTime.Today.ToString("dd/MM/yyyy");
}
the problem is that nothing is returned even when i try in server explorer with the correct date as a string nothing is returned. When it reaches the While loop this exception is thrown:
Any help would be very much appreciated

Your date format and the date delimiter is incorrect and spaces are missing:
private void ITemail()
{
string FinEmail;
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
dbConnector.Connect();
var sqlStr = "SELECT Created, [Action], ConnectionLoc, ConnectionSystem, Resource, [Text], RecordId, ToVal, ClientName "
+ "FROM tblAudit WHERE (ClientName = '" + Client + "') AND Created = #" + ToDate() + "#";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
txtIT.Text = dr[0].ToString() + dr[1].ToString() + dr[2].ToString() + dr[3].ToString() + dr[4].ToString() + dr[5].ToString() + dr[6].ToString()
+ dr[7].ToString() + dr[8].ToString();
}
}
private string ToDate()
{
return DateTime.Today.ToString("yyyy'/'MM'/'dd");
}

Related

MySQL update +- amount

I got this update thing i cant figure out. The save button seems to be working, its updating the table. I cant seem to figure out the SaveToStock method. It throws me this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''90' at line 1
I tried putting a breakpoint, got this. Break data
Save button
protected void saveButton_Click(object sender, EventArgs e)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySQLParser parser = new MySQLParser(connection);
int nonsoldamount = 0;
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
nonsoldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'", "amount"));
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
nonsoldamount = nonsoldamount + oldamount;
}
if (nonsoldamount < Convert.ToInt32(TextBoxAmount.Text))
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are only " + nonsoldamount + " in stock with the selected attributes</span>"));
return;
}
}
else
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are 0 in stock with the selected attributes</span>"));
return;
}
string sql_query = "";
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
sql_query = "UPDATE dpf_sale SET orderNo = ?orderNo, fk_operatorID = ?operator, status = ?status, amount = ?amount, geometry = ?geometry, length = ?length, CPSI = ?CPSI " +
"WHERE dpfSaleID = ?IDdpfSale";
}
else
{
sql_query = "INSERT INTO dpf_sale (orderNo, fk_operatorID, amount, geometry, length, CPSI, status) " +
"VALUES (?orderNo, ?operator, ?amount, ?geometry, ?length, ?CPSI, ?status)";
}
MySqlCommand myCommand = new MySqlCommand(sql_query, connection);
myCommand.Parameters.AddWithValue("?IDdpfSale", IDdpfSale);
myCommand.Parameters.AddWithValue("?orderNo", TextBoxOrderNo.Text);
myCommand.Parameters.AddWithValue("?operator", DropDownListOperator.SelectedValue);
myCommand.Parameters.AddWithValue("?geometry", DropDownListGeometry.SelectedValue);
myCommand.Parameters.AddWithValue("?length", DropDownListLength.SelectedValue.Replace(',', '.'));
myCommand.Parameters.AddWithValue("?status", DropDownListStatus.SelectedValue);
myCommand.Parameters.AddWithValue("?CPSI", DropDownListCPSI.SelectedValue);
myCommand.Parameters.AddWithValue("?amount", TextBoxAmount.Text);
myCommand.ExecuteNonQuery();
saveToStock();
}
editing = false;
IDdpfSale = 0;
Response.Redirect("dpf_sale.aspx");
}
Stock Change
private void saveToStock()
{
connection = new MySqlConnection(connectionString);
parser = new MySQLParser(connection);
connection.Open();
string sql_stock = "";
string sql_log = "";
int newsaleID;
if (editing == true)
{
sql_stock = "UPDATE dpf_stock SET amount = amount + " + oldamount + " - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
sql_log = "UPDATE dpf_stock_log SET amount = " + TextBoxAmount.Text + " WHERE sale = 1 and id = " + IDdpfSale;
}
else
{
newsaleID = Convert.ToInt32(parser.readSelectCommand("SELECT MAX(dpfSaleID) id FROM dpf_sale", "id"));
sql_log = "INSERT INTO dpf_stock_log (id, assembly, sale, amount) VALUES (" + newsaleID + ", 0, 1, " + TextBoxAmount.Text + ")";
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
sql_stock = "UPDATE dpf_stock SET amount = amount - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
}
else
{
return;
}
}
MySqlCommand myCommand1 = new MySqlCommand(sql_stock, connection);
myCommand1.ExecuteNonQuery();
MySqlCommand myCommand2 = new MySqlCommand(sql_log, connection);
myCommand2.ExecuteNonQuery();
connection.Close();
}

OleDbException was Unhandled - Crashes after a mins

After approximately 40 seconds of running this code and inserting ~400 records into the table I get a
OleDbException was Unhandled - Unspecified Error.
A copy of the code:
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
string sqlStr;
dbConnector.Connect();
sqlStr = " SELECT MAX(EventID) AS MaxID" +
" FROM Events";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
EventID = Convert.ToInt16( dr[0].ToString());
}
dr.Close();
sqlStr = " SELECT MemberID" +
" FROM GroupMembers" +
" WHERE (GroupID = " + GroupID + ")";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
MemberID = Convert.ToInt16( dr[0].ToString());
clsDBConnector dbConnectorInsert = new clsDBConnector();
string cmdStr = "INSERT INTO EventsAtendees " +
"(MemberID, EventID) " +
"VALUES (" + MemberID + ", " + EventID + ")";
dbConnectorInsert.Connect();
dbConnectorInsert.DoDML(cmdStr);
dbConnectorInsert.close();
}
dr.Close();
I have taken out the custom fields and variables to make this more useable by everyone.

Data type mismatch in criteria expression in WPF Application

Please help me out in this error.
I am using access database in C# and developing WPF application. Here, I am writing updating query and i got the below error :-
"Data type mismatch in criteria expression".
Here, Retail and Cut_Off both are checkbox. I added it later.When I added checkbox later it gives me this error.
I stored checkbox value like below :-
cmentity.Retail = chkRetailIndividualBidder.IsChecked.Value.ToString();
cmentity.Cut_Off = chkCutOff.IsChecked.Value.ToString();
Below code wrote in Clientmasterrepository.cs file
public int UpdateForAllClientInfo(ClientMaster cmentity)
{
string strQuery = "UPDATE ClientMaster SET " +
"Applied_Quantity = '" + cmentity.Applied_Quantity + "', " +
"Amount = '" + cmentity.Amount + "', " +
"Cheque_in_Favour = '" + cmentity.Cheque_in_Favour + "', " +
"Retail_Individual_Bidder = '" + cmentity.Retail + "', " +
"Cut_Off = '" + cmentity.Cut_Off + "' " +
"WHERE IsDeleted = " + 0;
return oConnectionClass.ExecuteNonQuery(strQuery);
}
below code wrote in connection.cs file:-
public int ExecuteNonQuery(string strQuery)
{
OleDbConnection oleDbConnection = new OleDbConnection(strConnectionString);
OleDbCommand oleDbCommand = new OleDbCommand(strQuery, oleDbConnection);
oleDbCommand.CommandText = strQuery;
oleDbCommand.CommandType = CommandType.Text;
oleDbConnection.Open();
oleDbCommand.ExecuteNonQuery();
oleDbConnection.Close();
return 1;
}

ORA:00933 SQL Command Not Properly Ended Error, while syncing Oracle and SQL Databases through C#.Net Application

I'm trying to update a table from Oracle Database to a table in SQL Server. But I'm getting an error:
ORA-00933 SQL COMMAND NOT PROPERLY ENDED.
I've tried every way to deal with it but not getting any solution.
static void Main(string[] args)
{
OleDbConnection conOracle = new OleDbConnection(connectionString);
conOracle.Open();
SqlConnection conSql = new SqlConnection(conStr);
conSql.Open();
//data set for Updation in CwsFaultyOracleSqlSYN Table in SQL
DataSet dsCWS = new DataSet();
string strUPDCWS = "SELECT SERIALNUMBER, GROUPCODE, PARTNO, RECCHALLANNO, RECDATE, FROMBRANCH, ";
strUPDCWS += " RECHUB, DEFSRNO, OKSRNO, FCRNO, FCRDATE, RECDTYPE, SEQNUMBER ";
strUPDCWS += " FROM CwsFaultyOracleSqlSYN WHERE INSFLG='N' ";
OleDbCommand cmdUPDCWS = new OleDbCommand(strUPDCWS, conOracle);
OleDbDataAdapter adpUPDCWS = new OleDbDataAdapter();
adpUPDCWS.SelectCommand = cmdUPDCWS;
adpUPDCWS.Fill(dsCWS, "table1");
//DataSet dsSqlUPDCWS = new DataSet();
string strSQLUPDCWS = "";
string OLEupdCWS = "";
if (dsCWS.Tables[0].Rows.Count > 0)
{
foreach (DataRow i in dsCWS.Tables[0].Rows)
{
try
{
strSQLUPDCWS = "UPDATE CwsFaultyOracleSqlSYN SET GROUPCODE='" + i["GROUPCODE"].ToString().Trim() + "', PARTNO='" + i["PARTNO"].ToString().Trim() + "',";
strSQLUPDCWS += " RECCHALLANNO='" + i["RECCHALLANNO"].ToString().Trim() + "',RECDATE='" + i["RECDATE"].ToString().Trim() + "',FROMBRANCH='" + i["FROMBRANCH"].ToString().Trim() + "',RECHUB='" + i["RECHUB"].ToString().Trim() + "',";
strSQLUPDCWS += " DEFSRNO='" + i["DEFSRNO"].ToString().Trim() + "',OKSRNO='" + i["OKSRNO"].ToString().Trim() + "',FCRNO='" + i["FCRNO"].ToString().Trim() + "',FCRDATE='" + i["FCRDATE"].ToString().Trim() + "',RECDTYPE='" + i["RECDTYPE"].ToString().Trim() + "',SERIALNUMBER='" + i["SERIALNUMBER"].ToString().Trim() + "'";
strSQLUPDCWS += " WHERE SEQNUMBER='" + i["SEQNUMBER"].ToString().Trim() + "'";
SqlCommand cmdUPDSqlCWS = new SqlCommand(strSQLUPDCWS, conSql);
cmdUPDSqlCWS.ExecuteNonQuery();
//Updating Flag in Oracle Database
OLEupdCWS = "UPDATE CwsFaultyOracleSqlSYN SET INSFLG='Y' AND INSDATE = SYSDATE WHERE SEQNUMBER='" + i["SEQNUMBER"].ToString().Trim() + "'";
OleDbCommand cmdOraceUpd = new OleDbCommand(OLEupdCWS, conOracle);
cmdOraceUpd.ExecuteNonQuery();
}
}
}
}
Well, I think this row:
OLEupdCWS = "UPDATE CwsFaultyOracleSqlSYN SET INSFLG='Y' AND INSDATE = SYSDATE WHERE SEQNUMBER='" + i["SEQNUMBER"].ToString().Trim() + "'";
Should be this:
OLEupdCWS = "UPDATE CwsFaultyOracleSqlSYN SET INSFLG='Y' WHERE SEQNUMBER='" + i["SEQNUMBER"].ToString().Trim() + "' AND INSDATE = SYSDATE ";
Note: your AND was before the WHERE.
Also, as mentioned in the comments, you really should use parameters when dealing with databases, unless you want a visit from little bobby tables.

SqlDataReader returns x rows but SQL query returns y rows

First time post as I'm a bit stuck here.
I am using this code to return some rows from a SQL Server database:
public static SqlDataReader SQLSelect(string sqlcommand, string[,] parameters, int length)
{
try
{
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
SqlDataReader reader;
SqlCommand cmd = new SqlCommand(sqlcommand, conn);
var allLength = parameters.Length;
for (int i = 0; i < parameters.Length - length; i++)
{
string paramid = parameters[i, 0];
if (paramid == "#date" || paramid == "#Date" || paramid == "#DATE")
{
string paramvalue = parameters[i, 1];
DateTime date = Convert.ToDateTime(paramvalue);
paramvalue = date.ToString("yyyy-MM-dd HH':'mm':'ss");
cmd.Parameters.Add(new SqlParameter(paramid, paramvalue));
}
else
{
string paramvalue = parameters[i, 1];
cmd.Parameters.Add(new SqlParameter(paramid, paramvalue));
}
}
cmd.CommandType = CommandType.StoredProcedure;
reader = cmd.ExecuteReader();
return reader;
}
catch
{
return null;
}
}
This function is called like so
string[,] parameters = new string[1, 2] { { "#studentid", studentid } };
SqlDataReader reader = Common.SQLSelect(Common.tblstudentprogressselectforprinting, parameters, 1);
now all runs fine except the reader only contains 13 rows of data where as the actual query being
exec sp_tblstudentprogress_selectforprinting #studentid=N'87'
as an example, returns 91 rows.
I'm at a loss as to why this is the case. Only thing I have noticed is when using SQL Server profiler, running the query from SQL Server, there is a RPC: Started and Completed, as for running from withing my web app, there is only an RPC: Started.
Any thoughts on this?
EDIT:
here is how I enumerate the reader
protected void btnPrint_Click(object sender, EventArgs e)
{
string[,] parameters = new string[1, 2] { { "#studentid", studentid } };
SqlDataReader reader = Common.SQLSelect(Common.tblstudentprogressselectforprinting, parameters, 1);
string firstname = txtFirstName.Text;
string lastname = txtLastName.Text;
int i=0;
string[] heading1 = new string[reader.FieldCount];
string[] heading2 = new string[reader.FieldCount];
string[] log = new string[reader.FieldCount];
try
{
while (reader.Read())
{
heading1[i] = "Progress Log for: Block: " + reader["block"].ToString() + " Lesson: " + reader["lesson"].ToString();
heading2[i] = "";
log[i] =
/*"PROGRESS LOG for " + reader["firstname"].ToString() + " " + reader["lastname"].ToString() + " Printed on " + DateTime.Today.ToShortDateString() + Environment.NewLine +*/
Environment.NewLine +
"Teacher: " + reader["teacher"].ToString() + Environment.NewLine +
"Date: " + reader["date"].ToString() + Environment.NewLine +
"Year: " + reader["year"].ToString() + Environment.NewLine +
"Block: " + reader["block"].ToString() + Environment.NewLine +
"Lesson: " + reader["lesson"].ToString() + Environment.NewLine +
"Warm Up: " + reader["warmup"].ToString() + Environment.NewLine +
"Range: " + reader["range"].ToString() + Environment.NewLine +
"Technique Sheet: " + reader["techniquesheet"].ToString() + Environment.NewLine +
"Technique Other: " + reader["techniqueother"].ToString() + Environment.NewLine +
Environment.NewLine +
"Notes: " + reader["notes"].ToString() + Environment.NewLine +
Environment.NewLine +
"Mark: " + reader["mark"].ToString()+ Environment.NewLine ;
i++;
}
}
catch
{
}
finally
{
if (Common.conn != null)
{
Common.conn.Close();
}
}
Common.PDFCreateProgressLog("Progress log for: " + firstname + " " + lastname, "Progress log for: " + firstname + " " + lastname, "PDF_" + firstname + " " + lastname + "-" + DateTime.Today.ToString("yyyy-MM-dd") + ".pdf", "Progress log for: " + firstname + " " + lastname, log, heading1, heading2);
}
You are confusing the meaning of the FieldCount property. It identifies the number of Columns, not the number of Rows. You cannot determine the total number of rows from a streaming source like a Reader, without enumerating all of the rows first (at least once, anyway).
So you will need to extend your arrays each time (lists might be easier for this) you read a row from the Reader and test the Reader to se when there are no more rows.

Categories

Resources