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

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

Related

Connection error after update mysql value C#

so my idea was once user will be loged in it will add +1 to the other table and online value in my mysql. I have done code like it's bellow. Once I have debug. I have inserted username and password but once I have press login button it says Error Connection. I am sure I have did something wrong in code but cant get it sort. So am trying to get help from you guys. Thanks
private void loginBtn_Click(object sender, EventArgs e)
{
try
{
if (txtUsername.Text != "" && txtPassword.Text != "")
{
con.Open();
string query = "SELECT id,username,password,email,fullname,company,uploads,avatar,account_type FROM users WHERE username ='" + txtUsername.Text + "' AND password ='" + txtPassword.Text + "'";
MySqlDataReader row;
row = con.ExecuteReader(query);
if (row.HasRows)
{
while (row.Read())
{
Properties.Settings.Default.username = row["username"].ToString();
Properties.Settings.Default.email = row["email"].ToString();
Properties.Settings.Default.fullname = row["fullname"].ToString();
Properties.Settings.Default.company = row["company"].ToString();
Properties.Settings.Default.uploads = row["uploads"].ToString();
Properties.Settings.Default.user_avatar = row["avatar"].ToString();
MySqlCommand newcmd = new MySqlCommand("UPDATE company SET online = online + 1 WHERE name = '" + row["company"].ToString() + "'");
try
{
newcmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
con.Close();
MessageBox.Show(ex.Number.ToString() + " -> " + ex.Message.ToString());
return;
}
}
this.Hide();
dashboard dash = new dashboard();
dash.Show();
}
else
{
MessageBox.Show("Nie znaleziono użytkownika", "Information");
}
}
else
{
MessageBox.Show("Nazwa użytkownika lub hasło jest nie poprawne", "Information");
}
}
catch
{
MessageBox.Show("Błąd połączenia", "Information");
}
For your question, you have connection error when you log in.
The error may be that there is already an open data reader associated with this connection
which must be closed, so close the data reader connection.
You could try the following code to get it.
private void btn_Submit_Click(object sender, EventArgs e)
{
conn.Open();
try
{
if (txtUsername.Text != "" && txtPassword.Text != "")
{
string query = "SELECT id,username,password,email,fullname,company,uploads,avatar,account_type FROM users WHERE username ='" + txtUsername.Text + "' AND password ='" + txtPassword.Text + "'";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.ExecuteScalar();
MySqlDataReader row;
row = cmd.ExecuteReader();
string company=null;
if (row.HasRows)
{
while (row.Read())
{
Properties.Settings.Default.username = row["username"].ToString();
Properties.Settings.Default.email = row["email"].ToString();
Properties.Settings.Default.fullname = row["fullname"].ToString();
Properties.Settings.Default.company = row["company"].ToString();
Properties.Settings.Default.uploads = row["uploads"].ToString();
Properties.Settings.Default.user_avatar = row["avatar"].ToString();
company = row["company"].ToString();
MessageBox.Show(row["company"].ToString(), "Note", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
row.Close();
cmd.CommandText = "UPDATE company SET online = online + 1 WHERE name = '" + company + "'";
try
{
cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Number.ToString() + " -> " + ex.Message.ToString());
}
this.Hide();
dashboard dash = new dashboard();
dash.Show();
}
else
{
MessageBox.Show("Nie znaleziono użytkownika", "Information");
}
}
else
{
MessageBox.Show("Nazwa użytkownika lub hasło jest nie poprawne", "Information");
}
}
catch
{
MessageBox.Show("Błąd połączenia", "Information");
}
finally
{
conn.Close();
}
}
Result:

sqlite database is locked 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.

How to do if/else statement for fileUpload

Heyy all. I am trying to do an if/else statement for my fileupload function on my Edit Profile page in my ASP.net webpage.
Here is my code:
protected void btnContinue_Click(object sender, EventArgs e)
{
//Declaration of variable to update Profile Image
string imageName, newContact;
imageName = FileUpload1.FileName.ToString();
newContact = tbMobile.Text.ToString();
username = (String)Session["NonAdmin"];
MySqlConnection mcon = new MySqlConnection("server=182.50.133.91;user id=Jonathan;password=jon123;persistsecurityinfo=True;database=ajactrac_;allowuservariables=True");
MySqlDataAdapter sda = new MySqlDataAdapter("select * from pointofcontact where Username = '" + username.ToString() + "'", mcon);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count.ToString() == "1")
{
MySqlCommand command = mcon.CreateCommand();
MySqlCommand command1 = mcon.CreateCommand();
MySqlCommand command2 = mcon.CreateCommand();
MySqlCommand command3 = mcon.CreateCommand();
MySqlCommand command4 = mcon.CreateCommand();
MySqlCommand command5 = mcon.CreateCommand();
MySqlCommand command6 = mcon.CreateCommand();
MySqlCommand command7 = mcon.CreateCommand();
command.CommandText = "update pointofcontact set Password = ?pwd where Username = '" + username.ToString() + "'";
command1.CommandText = "update pointofcontact set FirstName = ?firstname where Username = '" + username.ToString() + "'";
command2.CommandText = "update pointofcontact set LastName = ?lastname where Username = '" + username.ToString() + "'";
command3.CommandText = "update pointofcontact set ContactNumber = ?contact where Username = '" + username.ToString() + "'";
command4.CommandText = "update pointofcontact set EmailAddress = ?email where Username = '" + username.ToString() + "'";
command5.CommandText = "update pointofcontact set Address = ?address where Username = '" + username.ToString() + "'";
command6.CommandText = "update pointofcontact set BackupContactNumber = ?backupnumber where Username = '" + username.ToString() + "'";
command7.CommandText = "update pointofcontact set ProfilePic = ?newimage where Username = '" + username.ToString() + "'";
mcon.Open();
if (tbNewPassword.Text == "")
{
command.Parameters.AddWithValue("?pwd", tbOldPassword.Text.Trim());
}
else
{
command.Parameters.AddWithValue("?pwd", tbNewPassword.Text.Trim());
}
if(tbNewFirstName.Text == "")
{
command1.Parameters.AddWithValue("?firstname", tbFirstName.Text.Trim());
}
else
{
command1.Parameters.AddWithValue("?firstname", tbNewFirstName.Text.Trim());
}
if(tbNewLastName.Text == "")
{
command2.Parameters.AddWithValue("?lastname", tbLastName.Text.Trim());
}
else
{
command2.Parameters.AddWithValue("?lastname", tbNewLastName.Text.Trim());
}
if(tbNewContact.Text == "")
{
command3.Parameters.AddWithValue("?contact", tbMobile.Text.Trim());
}
else
{
command3.Parameters.AddWithValue("?contact", tbNewContact.Text.Trim());
}
if(tbNewEmail.Text == "")
{
command4.Parameters.AddWithValue("?email", tbEmail.Text.Trim());
}
else
{
command4.Parameters.AddWithValue("?email", tbNewEmail.Text.Trim());
}
if(tbNewAddress.Text == "")
{
command5.Parameters.AddWithValue("?address", tbAddress.Text.Trim());
}
else
{
command5.Parameters.AddWithValue("?address", tbNewAddress.Text.Trim());
}
if(tbNewBackupContact.Text == "")
{
command6.Parameters.AddWithValue("?backupnumber", tbBackupContact.Text.Trim());
}
else
{
command6.Parameters.AddWithValue("?backupnumber", tbNewBackupContact.Text.Trim());
}
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + imageName);
command7.Parameters.AddWithValue("?newimage", imageName);
command.ExecuteNonQuery();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command3.ExecuteNonQuery();
command4.ExecuteNonQuery();
command5.ExecuteNonQuery();
command6.ExecuteNonQuery();
command7.ExecuteNonQuery();
mcon.Close();
string javaScript = "<script language=JavaScript>\n" + "alert('Profile Updated!');\n" + "</script>";
RegisterStartupScript("xyz", javaScript);
}
else
{
string javaScript = "<script language=JavaScript>\n" + "alert('Some Error Occured! Profile Not Updated!');\n" + "</script>";
RegisterStartupScript("xyz", javaScript);
}
tbNewPassword.Text = "";
}
I had planned to use the if else statement for my fileupload function such that if the user has not uploaded a new picture, he/she would be still able to update their profile.
Currently when I try to edit a user's profile, this error message comes out.
Before uploading files to any directory, it is good to have this statement before saving file.
if (!Directory.Exists(Server.MapPath("~/Images")))
Directory.CreateDirectory("~/Images");
add above statement before this line
FileUpload1.PostedFile.SaveAs(Server.MapPath(Path.Combine("~/Images", imageName)));

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?

Data gets Truncated from database

I am designing a Window based application in C# using VS2010 and SqlServer2008-r2. I am
using a service Based Database(.mdf),in it there is a table having four fields, if i Store
data in the table and close the application and re-run the application the data gets Lost.
Why so and how to get rid of it.
I am Using Following routine for saving
private void Save(object sender, EventArgs e)
{
Program.connection.Close();
bool k = srchpreventry();
try
{
if (k)
{
string query = " update orderform set Enrolment_Expected = " + textBox2.Text + ", Stock_on_Hand=" + textBox3.Text + ", Number_Required = "+ textBox4.Text + " where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
else
{
// Program.connection.Open();
string query = "insert into orderform(Name,Enrolment_Expected,Stock_on_Hand,Number_Required) values('" + textBox1.Text + "', '" + textBox2.Text + "', ' " + textBox3.Text + "',' " + textBox4.Text + "')";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
}
catch (Exception ae)
{
string str = ae.ToString();
MessageBox.Show(str);
}
finally
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
Program.connection.Close();
}
}
public bool srchpreventry()
{
Program.connection.Open();
string query = " Select name from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
dtr.Close();
return true;
}
else
{
dtr.Close();
return false;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Program.connection.Close();
Program.connection.Open();
string query = " Select * from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
textBox2.Text = dtr[1].ToString();
textBox3.Text = dtr[2].ToString();//GetString(2);
textBox4.Text = dtr[3].ToString();
}
else
{
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
public static SqlConnection connection = null;
static string appath = Library_Records.Program.app_path;
string connectionstring = string.Format(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;User Instance=True", appath);
static string dbfiles = null;
internal static string app_path
{
get { return dbfiles = "|Datadirectory|\\records.mdf"; }
}
/*******************datagrid code********************/
Program.connection.Open();
string query = "select * from orderform";
SqlDataAdapter MyDA = new SqlDataAdapter();
MyDA.SelectCommand = new SqlCommand(query, Program.connection);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
Check to see if you can increase the characters allowed in the column for example nvarchar(max) cause now it could be nvarchar(200) - this is just an example
In Visual Studio?
You are not by chane having VIsual Studio load the same empty database again every time you start debug?
and close the application and re-run the application the data gets Lost.
Either someone ignores errors that get thrown on insert, does not commit a transaction or tvisal studio just ocpies the same rdatabase template into the directory every time you start.
I strongly (emphasis on strongly) suggest that you start using stored procedures (either in code or in the database), but besides that.. you don't start a transaction or something similar?
Or post the Program.Connection class code into the question.

Categories

Resources