C# SQLite Database During Update - c#

My SQLite query hangs then locks during my ExecuteNonQuery() in WriteToDB() below. It only seems to lock during the UPDATE and has no problem with the INSERT. This is only running in a single thread. When it hangs, I can see the journal being created in the SQLite database directory as if it keeps trying to write. It throws a SQLiteException with ErrorCode=5, ResultCode=Busy.
public String WriteToDB()
{
String retString = "";
//see if account exists with this email
String sql = "";
bool aExists = AccountExists();
if (!aExists)
{
sql = "INSERT INTO accounts (email, password, proxy, type, description) VALUES ('" + Email + "', '" + Password + "', '" + Proxy + "', 'dev', '" + Description + "');";
retString = "Added account";
}
else
{
sql = "UPDATE accounts SET password='" + Password + "', proxy='" + Proxy + "', description='" + Description + "' WHERE (email='" + Email + "' AND type='dev');";
retString = "Updated account";
}
using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
{
dbconn.Open();
using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
{
sqlcmd.ExecuteNonQuery(); //this is where it locks. Only on update.
}
}
return retString;
}
//Test to see if Email exists as account
public bool AccountExists()
{
int rCount = 0;
String sql = "SELECT COUNT(email) FROM accounts WHERE email='" + Email + "' AND type='dev';";
using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
{
dbconn.Open();
using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
{
rCount = Convert.ToInt32(sqlcmd.ExecuteScalar());
}
}
if (rCount > 0)
return true;
return false;
}

Oh man I feel dumb. I thought I posted all relevant code but all the code I posted works just fine. I had:
SQLiteDataReader dbReader = sqlcmd.ExecuteReader()
instead of
using (SQLiteDataReader dbReader = sqlcmd.ExecuteReader())
In another function. I thought it was an issue with the UPDATE because that was the place where the lock took place. Thanks for the responses and hopefully this reminds reminds everyone to use using() blocks with SQLite the first time!

Related

Syntax error in INSERT INTO command on Visual Studio

I have an easy insert query, but visual studio return "Syntax error in INSERT INTO command", i copy+paste the exact same query in the db (access) and it work... Any help??
public void Create(string mail, string nickname, string password, string avatar)
{
OleDbConnection cn = new OleDbConnection(_connectionString);
OleDbCommand cmd = new OleDbCommand();
try
{
String PwdSHA256;
SHA256 mySHA256 = SHA256.Create();
byte[] hashValue = mySHA256.ComputeHash(Encoding.UTF8.GetBytes(password));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hashValue.Length; i++)
{
builder.Append(hashValue[i].ToString("x2"));
}
PwdSHA256 = builder.ToString();
cn.Open();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO utenti ([email],[nickname],[password],[avatar],[attivo]) " +
"VALUES ('" + mail + "', '" + nickname + "', '" + PwdSHA256 + "','', false)";
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Session["errore"] = ex;
System.Web.HttpContext.Current.Response.Redirect("ErrorPage.aspx");
this._errore = ex.Message;
}
finally
{
cmd = null;
cn.Close();
}
}
Using SQL queries directly in your code is not a good coding practice, use SQL procedures and pass the parameters to SQL.
And be clear, the error you are facing is an execution time error or a compilation.
Use dbo.Your_DB_Name.utenti or Your_DB_Name.utenti instead of utenti.
Wrap up your 'false'
Are you still using PwdSHA256 encryption
Maybe you should change
cmd.CommandText = "INSERT INTO utenti (email,nickname,password,avatar,attivo) " +
"VALUES ('" + mail + "', '" + nickname + "', '" + PwdSHA256 + "','', false)";
And make sure your column in database is same with your query

There is already an open Data Reader associated with this Command which must be closed first Exception

I am getting an exception called There is already an open Data Reader Associated with this command which must be closed first, I tried to look up solution on Google I tried using MARS=true in connection string and also kept everything inside USING but it didn't solved the problem.
i get an Exception in line
cm.ExecuteNonQuery();
public void UpdateActionSchedule(string actionScheduleKey, string note, string PEOPLE_CODE_ID)
{
using (SqlConnection con = new SqlConnection("server=123; database=abc; user id=qwe; password=qwe;"))
{
con.Open();
if (note == "" || note == null)
{
string UPDATE_COMPLETE = String.Format("UPDATE ACTIONSCHEDULE SET EXECUTION_DATE = '" + DateTime.Now + "', COMPLETED = 'Y', REVISION_OPID='WFLOW' where UNIQUE_KEY = '" + actionScheduleKey + "' and people_org_code_id='" + PEOPLE_CODE_ID + "'");
SqlCommand cd = new SqlCommand(UPDATE_COMPLETE, con);
cd.ExecuteNonQuery();
cd.Dispose();
}
else
{
string oriNote = "";
string GET_NOTE = String.Format("SELECT NOTE FROM ACTIONSCHEDULE WHERE people_org_code_id='{0}' and UNIQUE_KEY='{1}'", PEOPLE_CODE_ID, actionScheduleKey);
using (SqlCommand cmd = new SqlCommand(GET_NOTE, con))
{
// SqlDataReader dr = cmd.ExecuteReader();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
oriNote = dr["NOTE"].ToString();
}
note = oriNote + " " + note;
}
//string UPDATE = String.Format("UPDATE ACTIONSCHEDULE SET Note = '" + note + "' where UNIQUE_KEY = '" + actionScheduleKey + "' and people_org_code_id='" + PEOPLE_CODE_ID + "'");
//SqlCommand cm = new SqlCommand(UPDATE, con);
//cm.ExecuteNonQuery();
//cm.Dispose();
string UPDATE_COMPLETE = String.Format("UPDATE ACTIONSCHEDULE SET EXECUTION_DATE = '" + DateTime.Now + "',Note = '" + note + "', COMPLETED = 'Y', REVISION_OPID='WFLOW' where UNIQUE_KEY = '" + actionScheduleKey + "' and people_org_code_id='" + PEOPLE_CODE_ID + "'");
SqlCommand cmw = new SqlCommand(UPDATE_COMPLETE, con);
cmw.ExecuteNonQuery();
cmw.Dispose();
}
}
}
}
}
In the second half of the code, you have a loop over cmd / dr, and inside that loop, you use cmw with ExecuteNonQuery. That means you're trying to execute two commands at once. Since you've already completed the loop: just move that code outside the using on the dr.
However, it looks like you could also do all of this in a single round trip with better SQL.

Error while using MySqlTransaction for multiple inserts

I have a form in windows where I am doing insert statement for header and detail.
I am using MySqlTransaction for the form. When there is no error in header and detail the transaction gets committed but when there is an error in insert query of detail then the following error comes while rollback
There is already an open DataReader associated with this Connection
which must be closed first.
Here is my code.
public string Insert_Hardening_Measures_HdrANDDtl(BL_Vessel_Hardening_Measures objHdr, List<BL_Vessel_Hardening_Measures> objDtl)
{
string success = "true";
string success1 = "";
MySqlConnection MySqlConnection1 = new MySqlConnection(strCon);
MySqlConnection1.Open();
MySqlTransaction MyTransaction = MySqlConnection1.BeginTransaction();
MySqlCommand MyCommand = new MySqlCommand();
MyCommand.Transaction = MyTransaction;
MyCommand.Connection = MySqlConnection1;
try
{
MyCommand.CommandText = "insert into hardening_measures_hdr (Hardening_Measures_Hdr_id,Month,Year) values (" + objHdr.Hardening_Measures_Hdr_id + ",'" + objHdr.Month + "','" + objHdr.Year + "')";
MyCommand.ExecuteNonQuery();
for (int i = 0; i < objDtl.Count; i++)
{
MyCommand.CommandText = "insert into hardening_measures_dtl (Hardening_Measures_Dtl_id,Hardening_Measures_Hdr_id,Hardening_Measures_Mst_id,Value) values (" + objDtl[i].Hardening_Measures_Dtl_id + "," + objDtl[i].Hardening_Measures_Hdr_id + ",'" + objDtl[i].Hardening_Measures_Mst_id + ",'" + objDtl[i].Value + "')";
MyCommand.ExecuteNonQuery();
}
MyTransaction.Commit();
MySqlConnection1.Close();
}
catch
{
MyTransaction.Rollback();
}
return success;
}
Anybody who have come through this kind of problem please suggest something

Unable to send email update upon insertion of data

I'm trying to allow my webapp to send an email update whenever a data is being inserted into the database like the codes i'll show below.
This is a btnAssign where it will update the relevant database table and column with data
protected void btnAssign_Click1(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
String assign = ddlpid1.SelectedValue;
connAdd.Open();
var sql = "Update MemberReport Set assignto ='" + assign + "', caseprogress = 'ongoing' where memberreportID='" + lbmemberreportid.Text + "'";
using (var cmdAdd = new SqlCommand(sql, connAdd))
{
cmdAdd.ExecuteNonQuery();
}
sql = "Insert into PoliceReport(memberreportid) values('" + lbmemberreportid.Text + "')";
// sql = "Update PoliceAccount Set handle ='" + assign + "' where policeid ='" + ddlpid1.SelectedValue + "' OR '" + ddlpid2.SelectedValue + "'";
using (var cmdAdd = new SqlCommand(sql, connAdd))
{
cmdAdd.ExecuteNonQuery();
}
sql = "Update PoliceAccount Set handle ='" + lbmemberreportid.Text + "' where policeid ='" + ddlpid1.SelectedValue + "'";
// sql = "Update PoliceAccount Set handle ='" + assign + "' where policeid ='" + ddlpid1.SelectedValue + "' OR '" + ddlpid2.SelectedValue + "'";
using (var cmdAdd = new SqlCommand(sql, connAdd))
{
cmdAdd.ExecuteNonQuery();
}
}
The insertion / updating of database part is working fine. When i addthe smtp codes to send email by selecting a column, it didnt work.
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
//con.Open();
// get the records matching the supplied username or email id.
cmd = new SqlCommand("select * from PoliceAccount where handle='" + lbmemberreportid.Text + "'", connAdd);
dr = cmd.ExecuteReader();
cmd.Dispose();
if (dr.HasRows)
{
dr.Read();
StringBuilder strBody = new StringBuilder();
//Passing emailid,username and generated unique code via querystring. For testing pass your localhost number and while making online pass your domain name instead of localhost path.
strBody.Append("<a>Please be notified that you've been assigned a case to handle. Please proceed to the scene with immediate effect.</a>");
// sbody.Append("&uCode=" + uniqueCode + "&uName=" + txtUserName.Text + ">Click here to change your password</a>");
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("apr13mpsip#gmail.com", dr["email"].ToString(), "Case Pending", strBody.ToString());
//pasing the Gmail credentials to send the email
System.Net.NetworkCredential mailAuthenticaion = new System.Net.NetworkCredential("apr13mpsip#gmail.com", "Temasekpoly13");
System.Net.Mail.SmtpClient mailclient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
mailclient.EnableSsl = true;
mailclient.Credentials = mailAuthenticaion;
mail.IsBodyHtml = true;
mailclient.Send(mail);
dr.Close();
dr.Dispose();
cmd.ExecuteReader();
cmd.Dispose();
//con.Close();
lbmemberreportid.Text = "";
ddllocation.SelectedIndex = 0;
ddlnumber.SelectedIndex = 0;
ddlpid1.SelectedIndex = 0;
tbdetails.Text = "";
tbproperty.Text = "";
tbsuspect.Text = "";
ddlpid1.Visible = false;
LoadGrid();
lblmsg.ForeColor = System.Drawing.Color.Green;
lblmsg.Text = "MemberReportID" + Session["memberreportid"] + "has been successfully assigned";
}
connAdd.Close();
}
To make matter worse, the label where the message is suppose to appear did not appear. Which means after inserting the data, the code basically stop running. I added a txtFile in the link here if the code i pasted above is confusing.
I really still cant figure out why does my email not run after inserting the data into the database.
Regards.
you are reading dr["email"].ToString() but only select assignto column in your select sql statement . you can change the select sql statement to select both assignto and email columns .

C# Web Developer web service

So i am making a website as part of a college project in c# web developer and i am getting this error, this is the web service and it has been connected to the database i cannot seem to find the error:
**Error 1 Type or namespace definition, or end-of-file expected
Source Error:
Line 278: }
Line 279: }
Line 280:}**
Now where can i go from here? Removing it messes up the entire site and adding another bracket does not help.
using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Web.Services.Protocols;
using System.Xml.Linq;
[WebService(Namespace = "http://tempuri.org/")]
public class WebService : System.Web.Services.WebService
{
// Connection is initialized
OleDbConnection conn;
OleDbDataReader dbReader;
private void ConnectToDatabase()
{
// Creates a connection to the database
conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath("App_Data\\Sports Car Auction Database.accdb"));
// Opens the connection
conn.Open();
}
private void DisconnectDatabase()
{
// The connection is closed
conn.Close();
}
[WebMethod]
public string Login(string userName)
{
// Connects to the database
ConnectToDatabase();
try
{
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = ("Select Password FROM [Buyer Information] WHERE UserName = '" + userName + "'");
dbReader = cmd.ExecuteReader();
dbReader.Read();
// The result is read from the datareader and returned to the calling method
string result = (string)dbReader["Password"];
return result;
}
catch (OleDbException)
{
// Nothing is returned if there are exceptions
return null;
}
}
[WebMethod]
public DataSet ForgetPass(string userName)
{
try
{
// Connect to database
ConnectToDatabase();
// Info from the database is selected via the data adapter
OleDbDataAdapter adapter = new OleDbDataAdapter(#"SELECT [Secret Question], [Answer] From [Buyer Information] Where [UserName] = '" + userName + "'", conn);
// Dataset stores results
DataSet ds = new DataSet();
adapter.Fill(ds);
// Dataset is returned to calling method
return ds;
}
catch
{
// Nothing is returned if there are exceptions
return null;
}
}
[WebMethod]
// Method defines what will be recieved from ChangePassword.aspx
public void ChangePass(string Pass, string userName)
{
// Connects to the database
ConnectToDatabase();
// Values in the database are updated
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = (#"UPDATE [Buyer Information] SET [Password] = '" + Pass + "' WHERE UserName = '" + userName + "'");
cmd.ExecuteNonQuery();
// The connection is closed
DisconnectDatabase();
}
[WebMethod]
// Method define what values will be recieved form register.aspx
public void RegisterCustomer(string UserName, string Address, string Tel, string Email, string Ques, string Ans, string Pass)
{
// Connects to thedatabase
ConnectToDatabase();
// Values are inserted into the database
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO [Buyer Information] ([UserName], [Address], [Telephone], [Email], [Password], [Secret Question], [Answer]) VALUES ('" + UserName + "', '" + Address + "', '" + Tel + "', '" + Email + "', '" + Pass + "', '" + Ques + "', '" + Ans + "')";
cmd.ExecuteNonQuery();
// The connection is closed
DisconnectDatabase();
}
[WebMethod]
public DataSet ViewDetails(string userName)
{
try
{
// Connects to the database
ConnectToDatabase();
// The correct data is selected from the database using the data adapter
OleDbDataAdapter adapter = new OleDbDataAdapter(#" SELECT Address, Telephone, Email, [Secret Question], Answer FROM [Buyer Information] WHERE UserName = '" + userName + "'", conn);
// The sesults are stored in the dataset
DataSet ds = new DataSet();
adapter.Fill(ds);
// Dataset is returned to the calling method
return ds;
}
catch (OleDbException)
{
// Nothing is returned if there are exceptions
return null;
}
}
[WebMethod]
// This defines what values will be recieved from Details.aspx
public void UpdateCustomer(string userName, string Address, string Tel, string Email, string Ques, string Ans)
{
// Connects to the database
ConnectToDatabase();
// Updates the database
OleDbCommand cmd = new OleDbCommand(#"UPDATE [Buyer Information] SET [UserName] = '" + userName + "', [Address] = '" + Address + "', [Telephone] = '" + Tel + "', [Email] = '" + Email + "', [Secret Question] = '" + Ques + "', [Answer] = '" + Ans + "' WHERE [UserName] = '" + userName + "'", conn);
cmd.ExecuteNonQuery();
// The connection is closed
DisconnectDatabase();
}
[WebMethod]
public DataSet SelectItem()
{
try
{
ConnectToDatabase();
// Get the model values for the drop down list
OleDbDataAdapter da = new OleDbDataAdapter("SELECT Model FROM Car", conn);
DataSet ds = new DataSet();
da.Fill(ds, "Model");
return ds;
}
catch (OleDbException)
{
// Nothing is returned if there are exceptions
return null;
}
}
[WebMethod]
public DataSet selectCarInfo(string model)
{
try
{
// Connects to the database
ConnectToDatabase();
// Info is selected from the database via the data adapter
OleDbDataAdapter adapter = new OleDbDataAdapter(#"SELECT [Car Information].carID, [Car Information].Make, [Car Information].Description, [Car Information].[Starting Bid], [Car Information].[Closing Date] FROM [Car Information] WHERE Model = '" + model + "'", conn);
// The results are stored in dataset
DataSet ds = new DataSet();
adapter.Fill(ds);
// Dataset is returned to calling method
return ds;
}
catch
{
// Nothing is returned if there are exceptions
return null;
}
}
[WebMethod]
public decimal highestBidVal(int carID)
{
try
{
// Connects to the database
ConnectToDatabase();
// Selects highestBid to compare to Buyer Informations value
OleDbCommand cm = conn.CreateCommand();
cm.CommandText = ("SELECT [Bid Information].HighestBid FROM [Bid Information] WHERE carID = " + carID + "");
dbReader = cm.ExecuteReader();
dbReader.Read();
decimal highestBidValue = (decimal)dbReader["HighestBid"];
return highestBidValue;
}
catch (OleDbException)
{
// Nothing is returned if there are exceptions
return 0;
}
}
[WebMethod]
// Method that defines what will be recieved from AddNewItem.aspx
public void AddNewCar(string Make, string Model, string Description, decimal StartingBid, DateTime closeDate, string owner)
{
ConnectToDatabase();
OleDbCommand cmd = conn.CreateCommand();
// Values are inserted into the database
cmd.CommandText = (#" INSERT INTO [Car Information] ([Make], [Model], [Description], [Starting Bid], [Closing Date], [Owner]) VALUES ('" + Make + "', '" + Model + "', '" + Description + "', '" + StartingBid + "', '" + closeDate + "', '" + owner + "')");
cmd.ExecuteNonQuery();
// Closes the connection
DisconnectDatabase();
}
[WebMethod]
// Method that defines what will be recieved from PlaceBid.aspx
public void AddNewBid(int carid, string userName, decimal bidValue,
DateTime bidingDate)
{
ConnectToDatabase();
// Values are updated in the database
OleDbCommand cmd = new OleDbCommand(#"UPDATE [Bid Information] SET [carID] = '" + carid + "', [UserName] = '" + userName + "', [Highest Bid] = '" + bidValue + "', [Bid Date] = '" + bidingDate + "' WHERE [carID] = " + carid + "", conn);
cmd.ExecuteNonQuery();
// The connection is closed
DisconnectDatabase();
}
[WebMethod]
// Method that defines what values will be recieved from Placebid.aspx
public void AddBid(int carid, string userName, decimal bidValue, DateTime bidingDate)
{
ConnectToDatabase();
OleDbCommand cmd = conn.CreateCommand();
// Values are inserted into the database
cmd.CommandText = (#"INSERT INTO [Bid Information] ([carID], [UserName], [UserName], [HighestBid], [Biddate]) VALUES ('" + carid + "', '" + userName + "', '" + bidValue + "', '" + bidingDate + "')");
cmd.ExecuteNonQuery();
// Closes the connection
DisconnectDatabase();
}
}
}
The last closing bracket seems to be the one which would match the namespace. Removing it should do it.
You can try to format your code with control-k-d. If it works, then your brackets (and the amount of them) match.
If you still get an error, that means your code has more errors in it. You probably are indeed missing a using directive, but that is another error. You do need to remove that closing-bracket, since it has no open-bracket match.

Categories