OleDbException was Unhandled - Crashes after a mins - c#

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.

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near '2'.'

Im trying to insert this test data in my sql database and I'm getting this error: System.Data.SqlClient.SqlException: 'Incorrect syntax near '2'.'
Any ideas how to solve this?
DateTime date = DateTime.Now;
string test = "{'payload': {'businessName': 'COMPANY1', 'subscriberName': 'JOHN DOE', 'accountNumber': 'CY68005000121234567890123456', 'numberOfRecords': 1," +
"'currentBalance': 4195.5, 'transactions': [{'transactionNumber': 'TR00000000','sequenceNumber': '000','transactionCode': '305','actualDateTime': '201812041624'," +
"'transactionValueDate': '2018-12-04', 'transactionCurrencyCode': 'EUR', 'transactionAmount': -1149.5, 'balance': 4195.5, 'chequeNo': '', 'depositedBy': 'CY68005000121234567890123456'," +
"'customerReference': 'uniqueValue', 'paymentNotes': 'NOTES', 'exchangeRate': 0}]}, 'errors': null}";
trans = JsonConvert.DeserializeObject<HB_transactions>(test);
for (int i=0; i<trans.payload.transactions.Count; i++)
{
string query = "SELECT TransactionId FROM AABankTransTable";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dataReader = cmd.ExecuteReader();
bool exists = false;
while(dataReader.Read())
{
if(dataReader[0].ToString() == trans.payload.transactions[i].transactionNumber)
{
exists = true;
break;
}
}
dataReader.Close();
if (exists) continue;
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES ('" + trans.payload.transactions[i].transactionNumber + "', 'HB', " + args[0] + ", '" + trans.payload.transactions[i].transactionCurrencyCode + "', " +
trans.payload.transactions[i].transactionAmount + ", " + date + ", 0, '" + trans.payload.transactions[i].depositedBy + "', '" +
trans.payload.transactions[i].paymentNotes + "', " + DateTime.Parse(trans.payload.transactions[i].transactionValueDate) + ")";
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
Solved by using SQL parameters instead of string concatenation.
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES (#TransID, 'HB', #COMID, #curr, #amount, #dlDate, 0, #depositor, #Details, #TransDate)";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#TransID", trans.payload.transactions[i].transactionNumber);
cmd.Parameters.AddWithValue("#COMID", args[0]);
cmd.Parameters.AddWithValue("#curr", trans.payload.transactions[i].transactionCurrencyCode);
cmd.Parameters.AddWithValue("#amount", trans.payload.transactions[i].transactionAmount);
cmd.Parameters.AddWithValue("#dlDate", date);
cmd.Parameters.AddWithValue("#depositor", trans.payload.transactions[i].depositedBy);
cmd.Parameters.AddWithValue("#Details", trans.payload.transactions[i].paymentNotes);
cmd.Parameters.AddWithValue("#TransDate", DateTime.Parse(trans.payload.transactions[i].transactionValueDate));
cmd.ExecuteNonQuery();

OleDbDataReader does not read last record

I see 5 records to be inserted, but only 4 are inserted. The last record is not inserted, and I can not figure out why. Copying from one database to the other. First is an access database, the second is a sql server database.
OleDbCommand cmd2 = new OleDbCommand();
OleDbDataReader oledbReader2;
using (cmd2 = new OleDbCommand())
{
query = "SELECT ID, STRAATNAAM, 'NL' AS TAALCODE, PKANCODE, CITY FROM Temp_Unique_Streetnames WHERE TRIM(Temp_Unique_Streetnames.STRAATNAAM) <> '' AND ID > " + lastId.ToString() + " ORDER BY ID";
WriteToFile(query);
cmd2.CommandText = query;
cmd2.CommandType = CommandType.Text;
cmd2.Connection = cn2;
using (oledbReader2 = cmd2.ExecuteReader())
{
while (oledbReader2.Read())
{
try
{
counter += 1;
query = "insert into tblgeo_street ( autoid, street_id, language, country, city, streetname, zip) values (" + counter.ToString() +
" , " + oledbReader2.GetValue(0).ToString() +
" , 'NL', 23, " + oledbReader2.GetValue(4).ToString() +
" , '" + oledbReader2.GetValue(1).ToString().Replace('\'', 'ยด') + "'" +
" , " + oledbReader2.GetValue(3).ToString() + ") ";
OleDbCommand cmd3 = new OleDbCommand(query, cn3);
WriteToFile(query);
cmd3.ExecuteNonQuery();
}
catch (Exception errorException)
{
actionSucceedded = false;
//eventLog1.WriteEntry("Open db threw exception " + errorException.Message);
WriteToFile("insert tblgeo_street threw exception " + errorException.Message);
}
}
}
}

syntax error missing operator in date and time query expression

cmd.CommandText = "SELECT * FROM " + TableName + " WHERE"
+ " [TIME_STAMP]=#" + TimeStamp.ToString("dd-MM-yyyy HH:mm") + "#"
+ " AND [Slave_Id]='" + SlaveUnitID
+ " AND [Parameter]='" + Param
+ "' AND [Status]='" + Status
+ "' AND [Reading]='" + Reading + "'";
dr = cmd.ExecuteReader();
I am getting error in the above query.Tried but getting the same, Plz help it out
Try to use parameterized query
conn.Open();
string query = "SELECT * FROM " + TableName + " WHERE [TIME_STAMP] =#date "
+" AND [Slave_Id]=#sid AND [Parameter] =#param "
+" AND [Status] =#status AND [Reading] = #reading"
qlCommand cmd = new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("#date", TimeStamp);
cmd.Parameters.AddWithValue("#sid", SlaveUnitID);
cmd.Parameters.AddWithValue("#param", Param);
cmd.Parameters.AddWithValue("#status", Status);
cmd.Parameters.AddWithValue("#reading", Reading );
dr = cmd.ExecuteReader();

get row with same id but different value and display different value into different label asp.net

this work but i want to display if value exist, so user can see the value username and last_update in each label based on each process_id but they have same request_id. this code only display username and last_update for the one that based on username login only.how i can do that ?
using(SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["MESTrans"].ConnectionString))
{
//bool exists = false;
int exists;
con.Open();
foreach (GridViewRow row in GridView2.Rows)
{
int req_id = Convert.ToInt32(GridView2.DataKeys[row.RowIndex].Values[0]);
using (SqlCommand cmd = new SqlCommand("select count(*) from [CutPanelConfirmation] where req_id=#req_id and process_id=#process_id", con))
{
cmd.Parameters.AddWithValue("#process_id", Session["process_id"].ToString());
cmd.Parameters.AddWithValue("#req_id", req_id);
exists = (int)cmd.ExecuteScalar();
}
if (exists > 0)
{
query = "select * from CutPanelConfirmation where req_id=#req_id and process_id=#process_id";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#process_id", Session["process_id"].ToString());
cmd.Parameters.AddWithValue("#req_id", req_id);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((string)dr["process_id"] == "marker")
{
LabelNameMarker.Text = LabelNameMarker.Text + " " + dr[1].ToString();
LabelDateMarker.Text = LabelDateMarker.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "fabric")
{
LabelNameFabric.Text = LabelNameFabric.Text + " " + dr[1].ToString();
LabelDateFabric.Text = LabelDateFabric.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "cutting")
{
LabelNameCutting.Text = LabelNameCutting.Text + " " + dr[1].ToString();
LabelDateCutting.Text = LabelDateCutting.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "SPP")
{
LabelNameSPP.Text = LabelNameSPP.Text + " " + dr[1].ToString();
LabelDateSPP.Text = LabelDateSPP.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "kitting")
{
LabelNameKitting.Text = LabelNameKitting.Text + " " + dr[1].ToString();
LabelDateKitting.Text = LabelDateKitting.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "sew")
{
LabelNameSew.Text = LabelNameSew.Text + " " + dr[1].ToString();
LabelDateSew.Text = LabelDateSew.Text + " " + dr[3].ToString();
}
}
dr.Close();
}
con.Close();
}
}
posting [https://stackoverflow.com/users/7892938/nfh][NFH] answer
i just delete#process id from this query and it works as what i want! :
query = "select * from CutPanelConfirmation where req_id=#req_id and process_id=#process_id"; cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("#process_id", Session["process_id"].ToString()); cmd.Parameters.AddWithValue("#req_id", req_id); SqlDataReader dr = cmd.ExecuteReader();

Datareader Exception Thrown Database - DateTime

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

Categories

Resources