I am creating a hotel management system, in which i am supposed to fetch the room for a specific reason. I am fetching room_NO from booking table using tourist_CNIC field from the same table. But i always get 0, instead of getting proper room number, which i have assigned to all of the rooms. Bellow is my code:
private int Fetch_Room()
{
int number = 0;
try
{
String str = "SELECT room_NO FROM booking WHERE tourist_CNIC='" + cnic.Content.ToString() + "'";
MySqlDataAdapter da = new MySqlDataAdapter(str, con);
DataTable dt = new DataTable();
da.Fill(dt);
foreach(DataRow row in dt.Rows)
number = Convert.ToInt32(row.ItemArray[0]);
return number;
}
catch (Exception x) { MessageBox.Show("Error: " + x.Message); return number; }
}
You can use MySqlDataReader for this case. try below solution
rivate int Fetch_Room()
{
int number = 0;
try
{
String str = "SELECT room_NO FROM booking WHERE tourist_CNIC='" + cnic.Content.ToString() + "'";
MySqlCommand cmd = new MySqlCommand(str, con);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
number = (int)rdr.GetValue(0);
}
return number;
}
catch (Exception x) { MessageBox.Show("Error: " + x.Message); return number; }
}
Related
Good Day.
I have a stock list in mysql database
I then have a windows form where i can allocate stock to a certain job, i do this by pulling all from my parts list in mysql and checking if the item selected by the user is in stock, i then add that item to a list using listbox.Items.Add(myitem). In also ass the quantity the user wants to a different list.
When I allocate the stock to a job i create one string separated by ',' and store that to mysql and the same with my quantites resulting is a parts string that looks like: 'PART001,PART002,PART003' and my quantities like: '2,1,3'.
I then add that to a request list which the admin needs to approve.
My problem comes in where the request form is loaded, I pull these parts and quantity lists from mySql and split them wit myString.Split(',');
And I then just add them to another listbox, HOWEVER when i get the quantities that my stock table has available, I loop over the part numbers and pull the quantities but if I for example have my first part as item 3 in my stock table and my second item as my 1st item in my stock list, it will assign item 1's quantity to my item 3. So basically my loop does not assign the right values.
Here is my code for checking the values
ListBox lb = PartsListBox;
ListBox lbq = PartsQuanListBox;
String query = "SELECT * FROM parts WHERE partnum = '"+PartsSelectCb.Text.Trim()+"'";
String partnum = "N/A";
int quan = 0;
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
partnum = (String)dr["partnum"];
}
con.Close();
if(PartsSelectCb.Text == partnum)
{
quan = int.Parse(textBox1.Text);
if (quan > 0)
{
if (!lb.Items.Contains(PartsSelectCb.Text.Trim()))
{
lb.Items.Add(PartsSelectCb.Text.Trim());
lbq.Items.Add(textBox1.Text.Trim());
}
}
}
And here is my code for inserting those values into my request table
private void SendRequest()
{
String dte = DateTime.Now.ToShortDateString();
String g = "";
String h = "";
String a = "";
String b = "";
if (PartsListBox.Items.Count > 0)
{
foreach (var item in PartsListBox.Items)
{
g += item.ToString() + ",";
}
h = g.Substring(0, g.Length - 1);
}
if (PartsQuanListBox.Items.Count > 0)
{
foreach (var itemt in PartsQuanListBox.Items)
{
a += itemt.ToString() + ",";
}
b = a.Substring(0, a.Length - 1);
}
String query = "INSERT INTO partsbook VALUES (NULL,'" + h + "','" + b + "','"
+ ReqTxt.Text.Trim() + "','" + userN + "','" + dte + "','" +""+"','"+ "REQUEST" + "')";
MySqlConnection dataCon = new MySqlConnection(conString);
dataCon.Open();
MySqlCommand cmd = new MySqlCommand(query, dataCon);
try
{
cmd.ExecuteNonQuery();
pmf.CheckRequests();
this.Close();
}
catch (Exception r)
{
MessageBox.Show("ERROR :" + r.Message.ToString());
}
dataCon.Close();
MessageBox.Show("REQUEST SENT");
this.Close();
}
Then on the request side
private void GetStock()
{
String query = "SELECT * FROM parts";
String qtys = "";
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String nme = (String)dr["partnum"];
foreach(var item in UPartsListBox.Items)
{
if(item.ToString() == nme)
{
int q = (int)dr["qty"];
qtys += q.ToString() + ",";
}
}
}
con.Close();
string[] words = qtys.Split(',');
foreach(var word in words)
{
if(word != "")
{
SPartsQuanListBox.Items.Add(word);
}
}
}
User Request:
Admin View:
Stock Table:
I'm trying to select one specific row from my mysql database.
In SQL I'd just use
select * from endkunden where id = 2;
this works just fine, I get everything I want.
Now I want to do this in my c# code and save the data into a string list.
I tried doing it like this
public List<string> SelectListRow(string target, string table,string idef, int id)
{
string query = "SELECT " + target + " FROM " + table + " where "+ idef + " = " +id;
List<string> list = new List<string>();
if (this.OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
list.Add(Convert.ToString(dataReader[target]));
}
dataReader.Close();
this.CloseConnection();
return list;
}
return list;
}
Since this worked for selecting all columns in the table using
select compname from endkunden;
I assumed, that this would work with rows as well, but it doesn't. When using it like this
I use the following query:
select *
from endkunden
where id = 2
but now I get an error:
System.IndexOutOfRangeException
HResult=0x80131508
Nachricht = Could not find specified column in results: *
Quelle = MySql.Data
Stapelüberwachung:
at MySql.Data.MySqlClient.ResultSet.GetOrdinal(String name)
at MySql.Data.MySqlClient.MySqlDataReader.GetOrdinal(String name)
at MySql.Data.MySqlClient.MySqlDataReader.get_Item(String name)
at MySQL_Tests.DBAC.SelectListRow(String target, String table, String idef, Int32 id) in C:\Users\Murf\source\repos\MySQL Tests\MySQL Tests\DBAC.cs:line 187
at MySQL_Tests.Program.Main(String[] args) in C:\Users\Murf\source\repos\MySQL Tests\MySQL Tests\Program.cs:line 13
Nachricht means message, quelle means error, stapelüberwachung means .. i don´t know
Any ideas how to fix this?
Greetings,
Murf
Since you are passing * it seems that you want multiple columns instead of just the first one.
public List<string> SelectListRow(string target, string table,string idef, int id)
{
string query = "SELECT " + target + " FROM " + table + " where "+ idef + " = " +id;
List<string> list = new List<string>();
if (this.OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
for (int i = 0; i < dataReader.FieldCount; i++) {
{
list.Add(dataReader.GetString(i));
}
}
dataReader.Close();
this.CloseConnection();
return list;
}
return list;
}
That will get you the values that you require.
One additional thing I noticed is that if there is an exception that the connection data reader arent cleaned up. You can fix this by using try block with a finally clause or wrapping these in 'using' blocks.
Instead using the data reader with the column name use
dataReader.GetString(0) which would give the first column.
public List<string> SelectListRow(string target, string table,string idef, int id)
{
string query = "SELECT " + target + " FROM " + table + " where "+ idef + " = " +id;
List<string> list = new List<string>();
if (this.OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
list.Add(dataReader.GetString(0));
}
dataReader.Close();
this.CloseConnection();
return list;
}
return list;
}
I wrote a method which saves the content of a specific table to a text file. Unfortunately the names of the columns are not retrieved. "Only" the data of each cell is written to the text file.
How do i need to adapt my code to also include the name of the columns?
private void WriteSQLQueryOutputToTextFile(string DBUser, string DBUserPassword, string sqlQuery, string databaseName, string nameOfOutputFile, string nameOfRow0, string nameOfRow1, string nameOfRow2)
{
StreamWriter outputFile = new StreamWriter(dWTestResult + "\\DatabaseUpgradeCheck\\" + nameOfOutputFile);
using (SqlConnection sqlCon = new SqlConnection("Data Source=" + GetEnvironmentVariable.MachineName + "; Initial Catalog=" + databaseName + "; User ID=" + DBUser + "; Password=" + DBUserPassword + ";"))
{
SqlCommand command = new SqlCommand(sqlQuery, sqlCon);
sqlCon.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
outputFile.WriteLine(String.Format("{0}, {1}, {2}",
reader[nameOfRow0], reader[nameOfRow1], reader[nameOfRow2]));
}
}
catch (Exception ex)
{
logger.Debug(ex, "Writing Database Output to the text file failed");
}
finally
{
reader.Close();
outputFile.Close();
}
}
}
Add a count variable, and if count == 0 add the column names. It looks like you know the names of the columns already so you have a couple of options.
First option: Just write the name.
try
{
int count = 0;
while (reader.Read())
{
if (count == 0)
{
outputFile.WriteLine(String.Format("{0}, {1}, {2}",
nameOfRow0, nameOfRow1, nameOfRow2));
}
outputFile.WriteLine(String.Format("{0}, {1}, {2}",
reader[nameOfRow0], reader[nameOfRow1], reader[nameOfRow2]));
count++;
}
}
Or (if you don't know the column names) use reader.GetName(i):
try
{
int count = 0;
while (reader.Read())
{
// if this is the first row, read the column names
if (count == 0)
{
outputFile.WriteLine(String.Format("{0}, {1}, {2}",
reader.GetName(0), reader.GetName(1), reader.GetName(2)));
}
// otherwise just the data (including 1st row)
outputFile.WriteLine(String.Format("{0}, {1}, {2}",
reader.GetValue(0), reader.GetValue(1), reader.GetValue(2)));
count++;
}
}
hi i think you can use : reader.GetName('index') for example for first column : reader.GetName(0)
See more at this link : https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader.getname?view=netframework-4.7.2
Please try this and set data row and column name as your need.
using (SqlConnection sqlCon = new SqlConnection("Data Source=" + GetEnvironmentVariable.MachineName + "; Initial Catalog=" + databaseName + "; User ID=" + DBUser + "; Password=" + DBUserPassword + ";"))
{
SqlCommand command = new SqlCommand(sqlQuery, sqlCon);
sqlCon.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.fill(dt);
try
{
if(dt != null && dt.Rows.Count > 0)
{
string columnName = dt.Columns[0].ToString();
DataRow dr = dt.Rows[0];
}
}
catch (Exception ex)
{
logger.Debug(ex, "Writing Database Output to the text file failed");
}
finally
{
reader.Close();
outputFile.Close();
}
}
An error is thrown when there is no data in data base while converting a string value into int.
try {
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmdc.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drc[0].ToString();
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp[0].ToString();
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
If there is value its working fine.but when there is no value in data base there is an error msg.
System.FormatException: Input string was not in a correct format.
Use IsDBNull to check for null values
Create and destroy all your type instances that implement IDisposable in using blocks. This ensures that connections are always released and resources are cleaned up.
Do not use connections across a class. Create them when needed and then dispose of them. Sql Server will handle connection pooling.
Get the native types directly, not the string equivalent! See changes to GetInt32 instead of ToString on the data reader.
You should refactor this to use SqlParameter's and make the retrieval statement generic OR get both SUM values in 1 sql call.
There is an if (!Page.IsPostBack) statement, if none of this code does anything if it is a postback then check at the top of the page and do not execute the sql statements if it is a postback. Otherwise the code is making (possibly) expensive sql calls for no reason.
try
{
int companyA = 0,companyB=0;
using(var con = new SqlConnection("connectionStringHere"))
{
con.Open();
using(SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con))
using(SqlDataReader drc = cmdc.ExecuteReader())
{
if (drc.Read() && !drc.IsDBNull(0))
companyA = drc.GetInt32(0);
}
using(SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con))
using(SqlDataReader drcp = cmdcp.ExecuteReader())
{
if (drcp.Read() && !drcp.IsDBNull(0))
companyB = drcp.GetIn32(0);
}
}
// if you are not going to do anything with these values if its not a post back move the check to the top of the method
// and then do not execute anything if it is a postback
// ie: // if (Page.IsPostBack) return;
if (!Page.IsPostBack)
{
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companyA.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyB.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
Try to replace this
SELECT SUM(Credited_amount)
WITH
SELECT ISNULL(SUM(Credited_amount),0)
Also find one confusing code while converting Credited amount values
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
---------^^^^^
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
I don't know about your business requirement but What i think Instead of using credit_amount value companya_credit_amount should be use to show value for companyA variable right?
You should do 2 things:
string companya_credit_amount = "", comapnyb_credit_amount = "";
Before assigning the value to these string variable you should check for db null as following:
while (drc.Read())
{
companya_credit_amount = (drc[0] != DbNull.Value) ? drc[0].ToString() : "" ;
}
Similarely
while (drcp.Read())
{
companyb_credit_amount = (drcp[0] != DbNull.Value) ? drcp[0].ToString() : "";
}
Try it.
You need to initialize credit_amount to empty and check if db value is null as shown below:
try {
companya_credit_amount = string.Empty;
companyb_credit_amount = string.Empty;
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmd
c.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
I have a datagridview which is created by various action and user's manipulation of data. I want to insert all the data of the gridview to the database at once, I know I could try a code similar to this:
private void btnSaveProducts_Click(object sender, EventArgs e)
{
SqlConnection connection = DBConnectivity.getConnection();
if (connection != null)
{
try
{
for (int i = 0; i < dGvProducts.Rows.Count; i++)
{
string query = "INSERT INTO product (productName) " + "VALUES (#productName)";
SqlCommand command = DBConnectivity.getCommandForQuery(query, connection);
int result = command.ExecuteNonQuery();
Console.WriteLine(result + "");
}
// string query = "Insert into units(name,packing)values('" + txtNameUnit.Text + "' , '" + txtPackingUnit.Text + "')";
// SqlCommand command = DBConnectivity.getCommandForQuery(query, connection);
// int result = command.ExecuteNonQuery();
// Console.WriteLine(result + "");
}
catch (Exception ex)
{
}
finally
{
connection.Close();
}
}
}
As is, the code tries to execute a parameterized query but never assigns a value to the parameter. Even if you do, you never extract the cell values.
The code should look like this:
var query = "INSERT INTO product (productName) VALUES (#productName)";
using var(connection = DBConnectivity.getConnection())
using(var command = new SqlCommand(query, connection))
{
var productParam=command.Parameters.Add("#productName",SqlDbType.NVarChar,50);
connection.Open();
for (int i = 0; i < dGvProducts.Rows.Count; i++)
{
var productName=dGvProducts.Rows[i].Cells[somecolumn].Value;
productParam.Value=productName;
int result = command.ExecuteNonQuery();
Console.WriteLine(result);
}
}