when trying to open a connection to phpmyadmin server the program freezes - c#

I'm trying to get my application to work with the database which is online in a phpmyadmin sql server. when i start my application it needs to get the password from the database, but when it tries to open a connection the whole program just freezes and it stays like that for a long time. in each class in which i am using this i make a new connection i don't know if this could be a problem for this or not.
here underneath is the database class i am using for this.
class Database
{
private SqlConnection connection;
private string connectionstring = "Server=studmysql01.fhict.local;Uid=dbi413434;Database=dbi413434;Pwd=Koekjesdeeg;";
private string nfcId;
private int vak;
private int rij;
public Database()
{
connection = new SqlConnection(connectionstring);
}
public string GetPassword(string username)
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT password FROM Login WHERE username = '" + username + "'", connection);
string checkPassWord = Convert.ToString(cmd.ExecuteScalar());
connection.Close();
return checkPassWord;
}
public void MakeAccount(string userName, string passWord)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO LOGIN (USERNAME, PASSWORD) VALUES (#USERNAME, #PASSWORD)";
comm.Parameters.AddWithValue("#USERNAME", userName);
comm.Parameters.AddWithValue("#PASSWORD", passWord);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("account is not made");
}
connection.Close();
}
public void Change_Info(double rate, int maximum_stay, int row, int line)
{
string command;
connection.Open();
SqlCommand comm = connection.CreateCommand();
if (rate == 0)
{
command = "UPDATE General SET Maximum_Stay=#maximum_stay, Row=#row, Line=#line WHERE ID=1";
}
else if (maximum_stay == 0)
{
command = "UPDATE General SET Rate=#rate, Row=#row, Line=#line WHERE ID=1";
}
else if (row == 0)
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Line=#line WHERE ID=1";
}
else if (line == 0)
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Row=#row WHERE ID=1";
}
else
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Row=#row, Line=#line WHERE ID=1";
}
comm.CommandText = command;
comm.Parameters.AddWithValue("#rate", rate);
comm.Parameters.AddWithValue("#maximum_stay", maximum_stay);
comm.Parameters.AddWithValue("#row", row);
comm.Parameters.AddWithValue("#line", line);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("info is not updated in general");
}
connection.Close();
}
public void CheckForId(int id, int row, int line, bool taken, string target)
{
string queryUpdate = "UPDATE eventlog SET Rij=#row, Vak=#line, Beschikbaarheid=#taken, Parkeerdoel=#target WHERE ID=#id";
string queryInsert = "INSERT INTO eventlog (ID, Rij, Vak, Beschikbaarheid, Parkeerdoel) VALUES (#id, #row, #line, #taken, #target)";
string queryDelete = "DELETE * FROM eventlog WHERE id=#id";
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT id FROM eventlog WHERE ID=#id", connection);
cmd.Parameters.AddWithValue("#id", id);
string data = Convert.ToString(cmd.ExecuteScalar());
SqlCommand comm = connection.CreateCommand();
if (data == "")
{
comm.CommandText = queryInsert;
}
else if (Int32.Parse(data) == id)
{
comm.CommandText = queryUpdate;
}
else
{
comm.CommandText = queryDelete;
}
comm.Parameters.AddWithValue("#row", row);
comm.Parameters.AddWithValue("#line", line);
comm.Parameters.AddWithValue("#taken", taken);
comm.Parameters.AddWithValue("#target", target);
comm.Parameters.AddWithValue("#id", id);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("info is not correctly inserted checkForid");
}
connection.Close();
}
public double GetRate()
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT Rate FROM General WHERE ID=1", connection);
double rate = Convert.ToDouble(cmd.ExecuteScalar());
connection.Close();
return rate;
}
public void SetId(int id, string nfcId, string kenteken, int row, int line, DateTime begintTijd)
{
if (row != -1 || line != -1)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO INCHECK (Timestamp, NfcId, Kenteken, ParkeerRij, ParkeerVak) VALUES (#Timestamp, #NfcId, #Kenteken, #ParkeerRij, #ParkeerVak)";
comm.Parameters.AddWithValue("#Timestamp", begintTijd);
comm.Parameters.AddWithValue("#NfcId", nfcId);
comm.Parameters.AddWithValue("#Kenteken", kenteken);
comm.Parameters.AddWithValue("#ParkeerRij", row);
comm.Parameters.AddWithValue("#ParkeerVak", line);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("not correctly inserted Setid");
}
connection.Close();
}
}
public void GetVisitorInformation(string kenteken)
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT NfcId FROM INCHECK WHERE Kenteken=#kenteken", connection);
SqlCommand cmd2 = new SqlCommand("SELECT ParkeerVak FROM INCHECK WHERE Kenteken=#kenteken", connection);
SqlCommand cmd3 = new SqlCommand("SELECT ParkeerRij FROM INCHECK WHERE Kenteken=#kenteken", connection);
cmd.Parameters.AddWithValue("#kenteken", kenteken);
cmd2.Parameters.AddWithValue("#kenteken", kenteken);
cmd3.Parameters.AddWithValue("#kenteken", kenteken);
nfcId = Convert.ToString(cmd.ExecuteScalar());
vak = Convert.ToInt32(cmd2.ExecuteScalar());
rij = Convert.ToInt32(cmd3.ExecuteScalar());
connection.Close();
}
public void SetCheckOutId(int id, string kenteken, DateTime eindTijd)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO UITCHECK (Timestamp, NfcId, Kenteken, ParkeerRij, ParkeerVak) VALUES (#Timestamp, #NfcId, #Kenteken, #ParkeerRij, #ParkeerVak)";
comm.Parameters.AddWithValue("#Timestamp", eindTijd);
comm.Parameters.AddWithValue("#NfcId", nfcId);
comm.Parameters.AddWithValue("#Kenteken", kenteken);
comm.Parameters.AddWithValue("#ParkeerRij", rij);
comm.Parameters.AddWithValue("#ParkeerVak", vak);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("checkoutid is not correctly inserted");
}
connection.Close();
}
public void SetParkingTargets(string target)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO ParkingTargets (Targets) VALUES (#Targets)";
comm.Parameters.AddWithValue("#Targets", target);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("parking targets are not set");
}
connection.Close();
}
public void DeleteParkingTarget(string target)
{
string queryDelete = "DELETE FROM ParkingTargets WHERE Targets=#target";
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = queryDelete;
comm.Parameters.AddWithValue("#target", target);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("not deleted");
}
connection.Close();
}
public List<string> GetParkingTargets()
{
List<string> targets = new List<string>();
connection.Open();
SqlCommand cmd2 = new SqlCommand("SELECT COUNT(id) FROM ParkingTargets", connection);
int numberOfLines = Convert.ToInt32(cmd2.ExecuteScalar());
for (int i = 1; i <= numberOfLines; i++)
{
SqlCommand cmd = new SqlCommand("SELECT Targets FROM ParkingTargets WHERE ID=#id", connection);
cmd.Parameters.AddWithValue("#id", i);
targets.Add(Convert.ToString(cmd.ExecuteScalar()));
}
connection.Close();
return targets;
}
}

Related

How to update a quantity of an item if it already exists in database

I have a productstbl table consisting of Name,Quantity and other attributes.
When I want to buy a new item that is already present in productstbl table I need to update the Quantity.
SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Productstbl WHERE Name = #name", con);
con.Open();
cmdCount.Parameters.AddWithValue("#name", NameBox.Text);
int count = (int)cmdCount.ExecuteScalar();
con.Close();
if (count > 0)
{
SqlCommand cmd = new SqlCommand("SELECT Qunatity FROM Productstbl WHERE Name = #name, Quantity = #quantity", con);
con.Open();
cmd.Parameters.AddWithValue("#name", NameBox.Text);
int ExistingQTY = (int)cmdCount.ExecuteScalar(); // I get error here
}
cmd = new SqlCommand("INSERT INTO Historytbl (Name, Date, Price, Quantity, Total_Price, Sup_Name, Process, Retail_Price) VALUES (#name, #date, #price, #quantity, #total_price, #sup_name, #process, #retail_price)", con);
con.Open();
cmd.Parameters.AddWithValue("#name", NameBox.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#price", PriceBox.Text);
cmd.Parameters.AddWithValue("#quantity", ExistingQTY);
cmd.Parameters.AddWithValue("#total_price", TotalPriceBox.Text);
cmd.Parameters.AddWithValue("#sup_name", comboBox1.Text);
cmd.Parameters.AddWithValue("#process", "buy");
cmd.Parameters.AddWithValue("#retail_price", RetailPriceBox.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record inserted successfully");
DisplayData();
ClearData();
If you want to update a quantity of a product, it is best for to get the quantity in the database if it already exists the database.
I make a code example, you can have a look.
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("Juice");
comboBox1.Items.Add("Apple");
comboBox1.Items.Add("Milk");
ShowData();
}
public void ShowData()
{
string connstr = "connstr";
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
string cmd = "select * from Product";
DataSet set = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd, connection);
adapter.Fill(set);
dataGridView1.DataSource = set.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
string connstr = "connstr";
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Product WHERE Name = #Name", connection);
cmdCount.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
int count = (int)cmdCount.ExecuteScalar();
int i = 0;
if(count>0)
{
SqlCommand command = new SqlCommand("SELECT Quantity FROM Product WHERE Name = #Name",connection);
command.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
i = Convert.ToInt32(reader["Quantity"]);
}
}
SqlCommand updatecmd = new SqlCommand("Update Product set Quantity=#Quantity, Date=#Date where Name=#Name",connection);
updatecmd.Parameters.AddWithValue("#Quantity", i + numericUpDown1.Value);
updatecmd.Parameters.AddWithValue("#Date", DateTime.Now);
updatecmd.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
updatecmd.ExecuteNonQuery();
dataGridView1.DataSource = null;
ShowData();
MessageBox.Show("Update successfully");
}
else
{
SqlCommand insertcmd = new SqlCommand("insert into Product(Name,Quantity,Date,Price)values(#Name,#Quantity,#Date,#Price)",connection);
insertcmd.Parameters.AddWithValue("Name", comboBox1.SelectedItem.ToString());
insertcmd.Parameters.AddWithValue("#Quantity",numericUpDown1.Value);
insertcmd.Parameters.AddWithValue("#Date",DateTime.Now);
insertcmd.Parameters.AddWithValue("Price",Convert.ToInt32(textBox1.Text));
insertcmd.ExecuteNonQuery();
dataGridView1.DataSource = null;
ShowData();
MessageBox.Show("Insert successfully");
}
connection.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedItem.ToString()== "Juice")
{
textBox1.Text = "10";
}
if (comboBox1.SelectedItem.ToString() == "Apple")
{
textBox1.Text = "5";
}
if (comboBox1.SelectedItem.ToString() == "Milk")
{
textBox1.Text = "8";
}
}
Tested Result:

How to prevent 2 connection open in database?

I try something good code about prevent duplication of entries but I got error about connection. How can I fix this? Here's my code.
if(label1.Text == "" || label2.Text == "" || label3.Text == "") {
MessageBox.Show("Please Select Data");
} else {
String query = "Select * from Attendance where empIn=#empIn";
MySqlCommand cmd1 = new MySqlCommand(query, con);
cmd1.Parameters.AddWithValue("empIn", label2.Text);
MySqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows) {
MessageBox.Show("This Person has already IN");
} else {
insert();
}
}
}
public void insert()
{
int i;
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO Attendance (Name,Date,empIn)VALUES(#Name,#Date,#empIn)", con);
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label3.Text;
cmd.Parameters.Add("#Date", MySqlDbType.Date).Value = Convert.ToDateTime(label1.Text);
cmd.Parameters.Add("#empIn", MySqlDbType.VarChar).Value = label3.Text;
i = cmd.ExecuteNonQuery();
if (i > 0) {
MessageBox.Show("Data Inserted");
label2.Text = "";
label3.Text = "";
label4.Text = "";
} else {
MessageBox.Show("Not Deleted");
}
con.Close();
you can simply use the "using" state which will create and close the connection automatically
public object getQueryScaller(string sqlQuery)
{
object value = null;
using (SqlConnection conn = new SqlConnection(_connectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
value = cmd.ExecuteScalar();
}
}
return value;
}
This will Automatically control the connection problem you will have no need to take care of it. just passing the parameter into the function as SQL statement and it will work.

Textbox Auto Number generated in c# error

I am creating a simple product form in c#. while I generated auto number getting error what I tried so far i attached below.product id starts with 00001. I created a method Getproduct() inside the method I wrote the code.error displayed syntax error.
public void Getproduct() {
string sql;
SqlConnection con = new SqlConnection("server =.; initial catalog=product; integrated security=true");
SqlDataAdapter dr;
SqlDataReader dr1;
sql = "SELECT id,product_name,product_desc,price FROM product Order By id Desc";
SqlCommand com = new SqlCommand(sql, con);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read() == true) {
int id;
int pid;
id = (dr[0] + 1);
pid = id.ToString("00000");
else if IsDBNull(dr) {
pid = ("00001");
}
}
}
Try this code
public void Getproduct()
{
string sql;
SqlConnection con = new SqlConnection("server =.; initial catalog=product; integrated security=true");
SqlDataAdapter dapt;
SqlDataReader dr1;
sql = "SELECT id,product_name,product_desc,price FROM product Order By id Desc";
SqlCommand com = new SqlCommand(sql, con);
SqlDataReader dr = com.ExecuteReader();
int id;
string pid;
if (dr.Read() == true)
{
int val = 0;
Int32.TryParse(dr[0].ToString(),out val);
id = ( val + 1);
pid = id.ToString("00000");
}
else if( Convert.IsDBNull(dr) )
{
pid = ("00001");
}
}

C# - Error With Getting Data From mySQL Database

I am currently getting an error when trying to get data from mySQL:
Additional information: Could not find specified column in results: admin
My code is:
public int getLevel()
{
string sqlCommand = "Select level from users where username = 'admin'";
int value = 0;
MySqlConnection con = new MySqlConnection("host=111.222.111.222;user=MYUSERNAME;password=MYPASSWORD;database=tcg;");
MySqlCommand cmd = new MySqlCommand(sqlCommand, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
value += int.Parse(reader.GetString("admin"));
}
return value;
}
Try:
public int getLevel()
{
int value = 0;
using(MySqlConnection con = new MySqlConnection("host=45.37.80.181;user=MYUSERNAME;password=MYPASSWORD;database=tcg;"))
{
con.Open();
using(MySqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Select level from users where username = #ad";
cmd.Parameters.AddWithValue("#ad","admin");
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
value += int.Parse(reader[0]);
}
}
con.Close();
}
return value;
}
If you only have one admin, use:
public int getLevel()
{
int value = 0;
using(MySqlConnection con = new MySqlConnection("host=45.37.80.181;user=MYUSERNAME;password=MYPASSWORD;database=tcg;"))
{
con.Open();
using(MySqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Select level from users where username = #ad";//add Order by if you need to
cmd.Parameters.AddWithValue("#ad","admin");
value += Convert.ToInt32(com.ExecuteScalar());//this assumes you will get an integer value
}
con.Close();
}
return value;
}

Datagridview update cell at certain condition

I have a datagrid with column id, nama barang, jumlah, harga
I used a textbox to input the data from database access, but i want update jumlah = jumlah + 1 whenever I inputed another id that already in the datagrid, but I got confused. Already try the for each row and for int count row things
this is my code
private void button_Input_Click(object sender, EventArgs e)
{
if (textBoxKodeBarang.Text != "")
{
insert_Data();
}
else if (textBoxKodeBarang.Text == "")
{
MessageBox.Show("Kode barang tidak boleh kosong !");
}
else
{
MessageBox.Show("Kode barang yang anda masukan salah !");
}
}
cmd.ExecuteNonQuery();
conn.Close();
}
private void insert_Data()
{
string cmdText = "Insert into [temp_Transaksi] (ID, nama_barang, harga) select id, nama, harga from [barang] where id =#pId";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
cmd.Parameters.AddWithValue("#pId", textBoxKodeBarang.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
private void update_Data()
{
string cmdText = "Update [temp_Transaksi] set jumlah=jumlah+1 where id =#pId";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
cmd.Parameters.AddWithValue("#pId", textBoxKodeBarang.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}

Categories