C# - Error With Getting Data From mySQL Database - c#

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

Related

How to get an integer value from SQL database to a variable in windows forms (C#)?

I've created a form called BookSeat which takes no.of seats as an input and calculate the total fare.
Here's my code:
{
try
{
DB db = new DB();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [fare] FROM [dbo].[Train] WHERE name = '" + textBoxName.Text + "' ";
cmd.Connection = db.GetConnection();
db.openConnection();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int d = dr.GetInt32(0);
int noOfSeats = comboBoxNoOfSeats.SelectedIndex;
int totalfare;
totalfare = noOfSeats * d;
textBoxTotalFare.Text = totalfare.ToString();
db.closeConnection();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This shows and error : Invalid attempt to read when no data is present
SqlDataReader has the method called Read which reads all the data inside sqldatareader. But you have to call this function inside while loop.
try
{
DB db = new DB();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [fare] FROM [dbo].[Train] WHERE name = '" + textBoxName.Text + "' ";
cmd.Connection = db.GetConnection();
db.openConnection();
SqlDataReader dr = cmd.ExecuteReader();
While(dr.Read())
{
//Get value by using column name;
int d = Convert.ToInt32(dr["columnname"]);
int noOfSeats = comboBoxNoOfSeats.SelectedIndex;
int totalfare;
totalfare = noOfSeats * d;
textBoxTotalFare.Text = totalfare.ToString();
}
dr.Close();
db.closeConnection();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

when trying to open a connection to phpmyadmin server the program freezes

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

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

Displaying a single row from access database in c#

i have a project, and part of it asks the user to input the ID of the patient to show his/her details
This is my code
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=hospital database.accdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Patients";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbReader = dbCmd.ExecuteReader();
listBox1.Items.Clear();
if (dbReader.HasRows)
{
while (dbReader.Read())
{
if (dbReader["PatientID"] != DBNull.Value)
{
int anInteger;
anInteger = Convert.ToInt32(textBox7.Text);
anInteger = int.Parse(textBox7.Text);
if (anInteger == 101)
{
}
}
}
}
in the IF statement, i dont know what to write in it, to display on the row of the patient with this ID only
Please Help!!
Instead of selecting all rows, it is much more efficient to filter the one row you are looking for using a parameter and modifying your SQL statement as follows.
sql = "SELECT * FROM Patients WHERE PatientID = [pID]";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbcmd.Parameters.AddWithValue("pID", 101);
dbReader = dbCmd.ExecuteReader();
I would also suggest looking into the "using" clause. Here's a SO example.
sql = "SELECT Count(*) FROM Patients WHERE PatientID = #PID";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbcmd.Parameters.AddWithValue("#PID", 101);
Int32 Cnt = dbCmd.ExecuteScalar();
if ( Cnt > 0)
{
// Do Something
}
else { // Do something}
you have to use a variable to be sure that your ID was found and and break; to exit your loop once it was found
if (dbReader.HasRows)
{
bool found = false;
while (dbReader.Read())
{
if (dbReader["PatientID"] != DBNull.Value)
{
int anInteger;
anInteger = Convert.ToInt32(textBox7.Text);
anInteger = int.Parse(textBox7.Text);
if (anInteger == 101)
{
found = true ; Break;
}
}
}
}
int anInteger = Convert.ToInt32(textBox7.Text);
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=hospital database.accdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Patients where PatientID=#PatientID";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Parameters.AddWithValue("#PatientID",anInteger);
dbCmd.Connection = dbConn;
dbReader = dbCmd.ExecuteReader();
listBox1.Items.Clear();
while (dbReader.Read())
{
//now display the reader values here : sample
//TextBox1.Text=dbReader["name"].ToString();
}

How can I return multiple string values using while loop+

This is what I want:
A method that is within a class that will return iteratively the values of a certain column. This values will the be added to a combobox when the method is invoked. Here is my attempt:
public string FillCombo()
{
string connstring = "Data Source=HP\\SQLEXPRESS;Initial Catalog=Arana;Integrated Security=True";
string query = "Select * from categorias";
SqlConnection conn = new SqlConnection(connstring);
SqlCommand command = new SqlCommand(query, conn);
SqlDataReader read;
conn.Open();
read = command.ExecuteReader();
while (read.Read())
{
string combodata = read.GetString(1);
return (combodata);
}
return null;
}
however, when this method is invoked, it only returns the first row into de combobox, not the other values.
It's called yield
http://msdn.microsoft.com/en-us/library/vstudio/9k7k7cf0.aspx
From the manual
public static System.Collections.IEnumerable Power(int number, int exponent)
{
int result = 1;
for (int i = 0; i < exponent; i++)
{
result = result * number;
yield return result;
}
}
yield will send a collection of return results from inside a loop after the loop has completed.
You can close data connections using a try/finally block around the loop.
public IEnumerable FillCombo()
{
SqlConnection conn = new SqlConnection(connstring);
SqlCommand command = new SqlCommand(query, conn);
SqlDataReader read;
conn.Open();
read = command.ExecuteReader();
try
{
while (read.Read())
{
yield return read.GetString(1);
}
}
finally
{
read.close();
conn.close();
}
}
A cool and often overlooked feature of C#
Consider using a List of string as an output. The following minor change to your code should help...
public List<string> FillCombo()
{
List<string> comboList = new List<string>();
string connstring = "Data Source=HP\\SQLEXPRESS;Initial Catalog=Arana;Integrated Security=True";
string query = "Select * from categorias";
SqlConnection conn = new SqlConnection(connstring);
SqlCommand command = new SqlCommand(query, conn);
SqlDataReader read;
conn.Open();
read = command.ExecuteReader();
while (read.Read())
{
string combodata = read.GetString(1);
comboList.Add(combodata);
}
return comboList;
}
Good Luck!

Categories