sqlite database is locked C# - c#

So i have this "database is locked" exception since yesterday. Tried everything i found here, yet still nothing. I'm using two forms - simple login form and then another one, where user can add new product to database. Checking if product already exist in db works, but adding new one throws that exception. Check it out please:
try
{
using (SqliteConnection db = new SqliteConnection("Filename=Magazyn.sqlite"))
{
db.Open();
string SQLcheck = "select * from Administrator";
using (SqliteCommand cmd = new SqliteCommand(SQLcheck, db))
{
using (SqliteDataReader reader = cmd.ExecuteReader())
{
var count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count > 0 && textBox1 != null && !string.IsNullOrWhiteSpace(textBox1.Text))
{
string sql = "select * from Administrator WHERE Name='" + textBox1.Text +
"' AND Password ='" + textBox2.Text + "'";
using (SqliteCommand command = new SqliteCommand(sql, db))
{
using (SqliteDataReader rdr = command.ExecuteReader())
{
if (rdr.Read())
{
MessageBox.Show(textBox1.Text + ", zostałeś pomyślnie zalogowany", "Logowanie");
AddProduct a = new AddProduct();
a.ShowDialog();
this.Close();
return;
}
else
{
MessageBox.Show("Nie ma administratora o loginie " + textBox1.Text +" lub Twoje hasło jest niepoprawne", "Błąd logowania");
textBox1.Clear();
textBox2.Clear();
}
}
}
}
else if (count == 0)
{
MessageBox.Show(
"W systemie nie istnieje konto administratora - nastąpi przekierowanie do formularza rejestracyjnego",
"Pierwsze logowania - konieczna rejestracja");
AddAdmin a = new AddAdmin();
a.ShowDialog();
return;
}
}
}
db.Close();
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
And 2nd Form:
try
{
using (SqliteConnection db = new SqliteConnection("Filename = Magazyn.sqlite"))
{
db.Open();
string sqlCheck = "select * from Produkty WHERE RFID='" + RFID.Text + "'";
using (SqliteCommand cmd = new SqliteCommand(sqlCheck, db))
{
using (SqliteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
MessageBox.Show("W bazie produktów jest już produkt o podanym tagu RFID", "Wykryto duplikat");
RFID.Clear();
}
else
{
reader.Close();
reader.Dispose();
string sql = "INSERT INTO Produkty (Name, RFID, Price, Unit, VAT) values ('" + Nazwa.Text + "','" +
RFID.Text + "','" + Cena.Text + "','" + Jednostka.Text + "','" + VATcat + "');";
//string sql = #"INSERT INTO Produkty (Name, RFID, Price, Unit, VAT) values (#name, #RFID, #price, #unit, #vat)";
using (SqliteCommand command = new SqliteCommand(sql, db))
{
using (SqliteDataReader rdr = command.ExecuteReader())
{
MessageBox.Show("Pomyślnie dodano produkt " + Nazwa.Text + " do bazy danych", "Dodano produkt");
}
/* command.CommandText = sql;
command.Connection = db;
command.Parameters.Add(new SqliteParameter("#name", Nazwa.Text));
command.Parameters.Add(new SqliteParameter("#RFID", RFID.Text));
command.Parameters.Add(new SqliteParameter("#price", Cena.Text));
command.Parameters.Add(new SqliteParameter("#unit", Jednostka.Text));
command.Parameters.Add(new SqliteParameter("#vat", VATcat));
command.ExecuteNonQuery();
MessageBox.Show("Pomyślnie dodano produkt " + Nazwa.Text + " do bazy danych", "Dodano produkt");
*/
}
}
}
}
db.Close();
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
I commented another way of adding to db (Will test both when I get rid of that exception)
Funny thing that if i change INSERT to SELECT it's working. If I use INSERT query directly in database file it's working too.

Related

Update SQL Server table columns with button click from gridview fields

I have a gridview that displays all the fields from my table.
My problem is that I need to update my SQL Server table when I click the save button (onclick) because I added a new field that generates a unique ID to every Item I have in my table. And It will add the generated id to the database table whenever I click the save button.
I have tried this
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text +
"' , [prno], [itemaname], [specification], [qty], [uomid], [expenseid],
[statusid], [userid], [inserteddate], [withquotation], [potempid] WHERE
idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
But I get an error
Here is my complete code:
public void SaveTogrdPOTemp()
{
SqlConnection ConnString = new SqlConnection(ConfigurationManager.ConnectionStrings["MUCS2.0ConnectionString"].ConnectionString);
string strSql = string.Empty;
pextid = "TPID";
using (SqlCommand cmd = new SqlCommand("SELECT * FROM GenIDGen WHERE extid = '" + pextid + "'"))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = ConnString;
ConnString.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
var extid = sdr["extid"].ToString().Trim();
var genID = sdr["generatedid"].ToString().Trim();
var gentr = sdr["generator"].ToString();
var potempoid = extid + genID;
ConnString.Close();
}
}
strSql = "UPDATE [dbo].[GenIDGen] SET [generator] = generator + 1
WHERE extid = '" + pextid + "' ";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text + "' WHERE idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
}
For the generating of ID and the updating of the gridview. Thank you!

C# Mysql Delay while updating/add/Get users in my program

Im writing a code which is saving users from a program in sql tables but when 15 users in one time are saving or updating im getting 1 min delay and program not responding... Can you help me. Its my code.
public bool GetUser(ref clsConnection c)
{
try
{
MySqlConnection connect = new MySqlConnection(connectionMysql);
connect.Open();
MySqlCommand query = new MySqlCommand("SELECT * FROM Users WHERE User_Name='" + Escape(c.Username) + "'", connect);
query.Prepare();
MySqlDataReader dr = query.ExecuteReader();
if (dr.Read())
{
c.Username = dr[1].ToString();
c.NoColPlyName = dr[2].ToString();
c.Cash = double.Parse(dr[3].ToString());
c.Password = dr[4].ToString();
}
else
{
dr.Close();
connect.Close();
return false;
}
dr.Close();
connect.Close();
return true;
}
}
public void UpdateUser(clsConnection u)
{
MySqlConnection cn = new MySqlConnection(connectionMysql);
try
{
if (u.Username != "")
{
cn.Open();
MySqlCommand query = new MySqlCommand(#"UPDATE Users SET User_Name=#User_Name,User_PlyName=#User_PlyName,User_Cash=#User_Cash,User_Passowrd=#User_Password WHERE User_Name='" + Escape(u.Username) + "';", cn);
if (query != null)
{
query.Parameters.AddWithValue("#User_Name", Escape(u.Username));
query.Parameters.AddWithValue("#User_PlyName", Escape(u.NoColPlyName));
query.Parameters.AddWithValue("#User_Cash", u.Cash);
query.Parameters.AddWithValue("#User_Passowrd", u.Password);
cn.Close();
return;
}
else
{
return;
}
}
}
}
public void AddUser(clsConnection c)
{
try
{
if (c.Username != "")
{
Query(#"INSERT INTO Users (User_Name,User_PlayerName,User_Cash,User_Passowrd) VALUES ('" +
Escape(c.Username) + "', '" +
Escape(c.NoColPlyName) + "', '" +
c.Cash + "', '" +
Espace(c.Passoword) + "');");
}
}
}
//when 15 users try to connect to program program not responding and delay is very big. When <10 users connected to program, program works good,but +10 delay is big...
You should put your query in a using statement like this:
using (MySqlConnection con = new MySqlConnection(connectionMysql))
{
con.Open();
using (MySqlCommand com = con.CreateCommand())
{
com.CommandText = "SELECT * FROM Users WHERE User_Name='" + Escape(c.Username) + "'";
using (MySqlDataReader dr = com.ExecuteReader())
{
if (dr.Read())
{
c.Username = dr[1].ToString();
c.NoColPlyName = dr[2].ToString();
c.Cash = double.Parse(dr[3].ToString());
c.Password = dr[4].ToString();
}
else
{
dr.Close();
connect.Close();
return false;
}
return true;
}
}
}
And then you can implement the same method to your UPDATE and INSERT queries

how can i merge two field in combobox

this is my code :
cmbSahebFa.Items.Clear();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select mID,mName from tblMoshtari";
objCon.Connecting();
cmd.Connection = objCon.con;
objCon.con.Open();
try
{
SqlDataReader objDataReader = cmd.ExecuteReader();
object[] x = new object[2];
while (objDataReader.Read())
{
objDataReader.GetSqlValues(x);
cmbSahebFa.Items.Add(x[1].ToString());
}
}
catch (Exception exp)
{
MessageBox.Show("Error") : " + exp.Message);
}
finally
{
objCon.con.Close();
}
i want to display both field in combo box.
how can i show two field mID+mName in combobox ?
cmbSahebFa.Items.Add(objDataReader[0].ToString() + " " + objDataReader[1].ToString());
or
SqlDataReader objDataReader = cmd.ExecuteReader();
object[] x = new object[2];
while (objDataReader.Read())
{
objDataReader.GetSqlValues(x);
cmbSahebFa.Items.Add(x[0].ToString()+ " " + x[1].ToString());
}
or by column name
SqlDataReader objDataReader = cmd.ExecuteReader();
while (objDataReader.Read())
{
cmbSahebFa.Items.Add(objDataReader["mID"].ToString() + " " + objDataReader["mName"].ToString());
}
Here is MSDN Reference on Retrieving Data Using DataReader.
I think, SQL concatination would be easier:
cmd.CommandText = "select mID + ' ' + mName from tblMoshtari";

How would you use multiple mysql queries in C#

try
{
string strConnection = "host=bla; database=twhalen_storage; username=twhalen_software; password=bla!;";
MySqlConnection conSQL = new MySqlConnection(strConnection);
MySqlCommand mycommand = new MySqlCommand("SELECT * FROM twhalen_storage.users WHERE username= '" + this.username_txt.Text + "'AND password= '" + this.password_txt.Text + "';", conSQL);
MySqlDataReader myReader;
conSQL.Open();
myReader = mycommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
}
else
MessageBox.Show("go away");
conSQL.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
How would I do multiple mysql queries using code similar to this?

recently stored data cannot be read by another method

I have added the data as:
public static void insert()
{
try
{
string connStr =
(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;
OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText =
"INSERT INTO patientinfo (medicareNo, title, fName, lName, gender, height, weight, age )" +
" VALUES(" + p.getMedicare() + ",'" + p.getTitle() + "','" + p.getfName() + "','" + p.getlName() +
"','" + p.getGender() + "'," + p.getheight() + "," + p.getweight() + "," + p.getAge() + ");";
conn1.Open();
cmd.ExecuteNonQuery();
//displayResult(medicareNo);
}
catch (OleDbException exp)
{
Console.WriteLine("Error");
}
displayResult(medicareNo);
}
and I have another method for reading data
public static void displayResult(int medicareNo )
{
try
{
string connStr =
(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;
OleDbCommand cmd1 = conn1.CreateCommand();
cmd1.CommandText = "SELECT * FROM patientinfo WHERE medicareNo = " + "" + medicareNo + "";
conn1.Open();
OleDbDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if (rdr.HasRows)
{
checkvalue = true;
foreach (DataRow row in rdr.GetSchemaTable().Rows)
{
Console.Write(row["ColumnName"].ToString() + " ");
}
Console.WriteLine(" ");
while (rdr.Read())
{
Console.Write(rdr["medicareNo"].ToString());
Console.Write(" ");
Console.Write(rdr["title"].ToString());
Console.Write(" ");
Console.Write(rdr["fName"].ToString());
Console.Write(" ");
Console.Write(rdr["lName"].ToString());
Console.Write(" ");
Console.Write(rdr["gender"].ToString());
Console.Write(" ");
Console.Write(rdr["height"].ToString());
Console.Write(" ");
Console.Write(rdr["weight"].ToString());
Console.Write(" ");
Console.WriteLine(rdr["age"].ToString());
Console.WriteLine(".......................");
}
Console.WriteLine("Patient registered. Information retrieved. ");
}
else
{
checkvalue = false;
Console.WriteLine("Patient not registered. Add Patient information for registration.");
}
}
catch (OleDbException exp)
{
Console.WriteLine("error.");
}
}
The problem is displayResult() cannot find the recently added data, so i cannot display it right after adding it. Even calling them separately in main() didnt work. It just goes to "patient not registered..................".Any suggestions please
update: get set method for medicareno.
public void SetMedicare(int pMedicare)
{
if (pMedicare > 0)
{
medicareNo = pMedicare;
}
else
{
Console.WriteLine("Medicare Number not valid");
}
}
public int getMedicare()
{
return medicareNo;
}
Your SELECT statement is the issue:
"SELECT * FROM patientinfo WHERE medicareNo = " + "" + medicareNo + ""
It is comparing medicareNo as a string, instead of as an int.
Change your query to this:
"SELECT * FROM patientinfo WHERE medicareNo = " + medicareNo
change displayResult(medicareNo); with below
displayResult(p.getMedicare());
And also I would change your methods as below
public static void insert()
{
try
{
string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\test.accdb;Persist Security Info=False";
string commandText = "INSERT INTO patientinfo (medicareNo, title, fName, lName, gender, height, weight, age )" +
" VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
using (OleDbConnection con = new OleDbConnection(connStr))
using (OleDbCommand cmd = new OleDbCommand(commandText, con))
{
cmd.Parameters.AddWithValue("#medicareNo", p.getMedicare());
cmd.Parameters.AddWithValue("#title", p.getTitle());
cmd.Parameters.AddWithValue("#fName", p.getfName());
cmd.Parameters.AddWithValue("#lName", p.getlName());
cmd.Parameters.AddWithValue("#gender", p.getGender());
cmd.Parameters.AddWithValue("#height", p.getheight());
cmd.Parameters.AddWithValue("#weight", p.getweight());
cmd.Parameters.AddWithValue("#age", p.getAge());
con.Open();
int ret = cmd.ExecuteNonQuery();
if(ret ==1)
Console.WriteLine("Insert Successful");
}
displayResult(p.getMedicare());
}
catch (OleDbException exp)
{
Console.WriteLine("Error");
}
}
public static void displayResult(int medicareNo)
{
try
{
string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\test.accdb;Persist Security Info=False";
string commandText = "SELECT * FROM patientinfo WHERE medicareNo = ?";
using (OleDbConnection con = new OleDbConnection(connStr))
using (OleDbCommand cmd = new OleDbCommand(commandText, con))
{
cmd.Parameters.AddWithValue("#medicareNo", medicareNo);
con.Open();
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
foreach (DataRow row in rdr.GetSchemaTable().Rows)
{
Console.Write(row["ColumnName"].ToString() + " ");
}
Console.WriteLine(" ");
while (rdr.Read())
{
string str = string.Format("{0} {1} {2} {3} {4} {5} {6} {7}",
rdr["medicareNo"], rdr["title"], rdr["fName"], rdr["lName"],
rdr["gender"], rdr["height"], rdr["weight"], rdr["age"]);
Console.WriteLine(str);
}
Console.WriteLine("Patient registered. Information retrieved. ");
}
else
{
Console.WriteLine("Patient not registered. Add Patient information for registration.");
}
}
}
}
catch (OleDbException exp)
{
Console.WriteLine("error.");
}
}

Categories

Resources