How to assign a mysql query result to a variable C# - c#

**Hello everyone, im fairly new with c# and am currently trying to make flappy bird in c# windows form application. I am trying to make a leaderboard. I want to save the highscores into a mysql database. But i dont know how to compare the score you get in game with the data in the database. The query works but i dont know how to get that result and assign that to the variable "lastleaderboardscore". Would you guys be able to help?
Thank you**
public partial class Form1 : Form
{
int pipeSpeed = 8;
int groundspeed;
int gravity = 8;
int score = 0;
int lives = 3;
int totalScore = 0;
private int tableOf = 5; //preset for the table of 5
int lastleaderboardscore;
int i;
Random rndHeight = new Random();
{
InitializeComponent();
string server = "localhost";
string database = "flappyLeader";
string dbUsername = "root";
string dbPassword = "";
string connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + dbUsername + ";" + "PASSWORD=" + dbPassword + ";";
MySqlConnection mysqlcon = new MySqlConnection(connectionString);
i = 0;
mysqlcon.Open();
MySqlCommand cmd = mysqlcon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select score from leaderboard order by Score desc limit 1 offset 9";
DataTable dtbl = new DataTable();
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
i = Convert.ToInt32(dtbl.Rows.Count.ToString());
lastleaderboardscore = ds.Tables[0].Rows[2].;
mysqlcon.Close();
Here you'll find the code where I compare the 2 variables "totalscore" (score in game) and "lastleaderboardscore"
if (lives == 0)
{
if (totalScore > lastleaderboardscore)
{
/* TextBox1.Show();*/
}
label4.Show();
label4.Text = "your total score is" + totalScore.ToString();
lives = 3;
pipeSpeed = 8;
label1.Text = "game Over";
totalScore = 0;
label3.Visible = false;
}

You can use datatable itself to get the result.
SqlCommand command = new SqlCommand(""Select score from leaderboard order by Score desc limit 1 offset 9", mysqlcon);
DataTable dtbl = new DataTable();
MySqlDataAdapter sda = new MySqlDataAdapter(command);
sda.Fill(dtbl);
lastleaderboardscore =dtbl.Rows(0).Item(0).ToString
This is the basic idea.

Related

C# - Trying to check if value exists in Access Database

I am creating a program that I will allow you to enter in a number and it will display the information in the respective row. However, if the number is not found in the num field, I want it to return with showing the text I set for a label (label12). However, I am getting returned with exception errors and I cannot figure out how to create this where if the num doesn't exist it will perform a set action.
olcn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\TestUser\Documents\testlist.mdb");
OleDbDataAdapter oda = new OleDbDataAdapter("select * from testlist where num = '"+textBox11.Text+"'", olcn);
DataTable dt = new DataTable();
oda.Fill(dt);
if (oda.Fill(dt).Equals(null))
{
label12.Show();
}
else if (!oda.Fill(dt).Equals(textBox11.Text))
{
textBox1.Text = dt.Rows[0][1].ToString();
textBox2.Text = dt.Rows[0][2].ToString();
textBox3.Text = dt.Rows[0][3].ToString();
textBox4.Text = dt.Rows[0][4].ToString();
textBox5.Text = dt.Rows[0][5].ToString();
textBox6.Text = dt.Rows[0][6].ToString();
textBox7.Text = dt.Rows[0][7].ToString();
textBox8.Text = dt.Rows[0][8].ToString();
textBox9.Text = dt.Rows[0][9].ToString();
textBox10.Text = dt.Rows[0][10].ToString();
bool v = String.IsNullOrEmpty(dt.Rows[0][11].ToString());
if (!v)
{
pictureBox1.Load(dt.Rows[0][11].ToString());
}
else
{
pictureBox1.Load(dt.Rows[0][12].ToString());
}
}
The result of the Fill() method is the number of rows returned. Just update your code to check the result of Fill() is greater than zero records.
olcn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\TestUser\Documents\testlist.mdb");
OleDbDataAdapter oda = new OleDbDataAdapter("select * from testlist where num = '"+textBox11.Text+"'", olcn);
DataTable dt = new DataTable();
int count = oda.Fill(dt);
if (count == 0)
{
label12.Show();
}
else
{
// ... your mapping logic
}
MS Documentation, OleDbDataAdapter.Fill Method

How do I pull data from mysql and assign it to corresponding values

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:

how to create an id to be shown in the text box based on selected dropdownlist

i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}

Using DataTable.update() does not add entries to my SQL Server database in one method but does in another

I have a method (AddRowToSQLTable()) that is passed a row, it then creates a row array containing that row and then passes it to DataTable.update().
This works fine. The SQL Server is updated and the next time I run (debug) the program the new data is present.
Another method (AddStock()) uses a similar structure but does not work.
The difference being that I am passing a data table in Update() not a Row[] however no exception is thrown just nothing is updated/added on the server.
Can someone please explain what exactly is going on and why these differ? I would like to know this even if the solution is to use a different structure to achieve what I want so I know for the future and have a better understanding.
To Note:
I have tested to ensure the DataTable being passed contains records. The DataTable is of the same format as the target SQL Server table.
I have also tried SqlBulkCopy and encounter the same problem.
Many thanks!
private DataTable StockAdditions;
public void PrepareStockQuantitiesForAdding()
{
if (StockAdditions != null)
{
StockAdditions.Clear();
}
StockAdditions = StockQuantitiesTable.Clone();
int Count = 0;
DataRow RowToAdd = StockQuantitiesTable.NewRow();
DataView AreaIDs = new DataView(AreaTable);
DataView Conditions = new DataView(ConditionsTable);
int AreaID;
string ConditionCode;
foreach (DataRow Row in SessionSKUScanned.Rows)
{
if (Row["Serial Number"].ToString() == "")
{
Conditions.RowFilter = "([Name] = '" + Row["Condition"] + "')";
ConditionCode = Conditions[0][2].ToString();
AreaIDs.RowFilter = "([StorageAreaName] = '" + Row["Area"] + "')";
AreaID = Convert.ToInt32(AreaIDs[0][0]);
DataView StockQuantities = new DataView(StockQuantitiesTable);
StockQuantities.RowFilter = "([QuantityID] = '" + AreaID + "-" + Row["SKU"] + "-" + ConditionCode + "')";
if (StockQuantities.Count > 0)
{
StockQuantities[0][3] = Convert.ToInt32(StockQuantities[0][3]) + 1;
RowToAdd["QuantityID"] = AreaID + "-" + Row["SKU"] + "-" + ConditionCode;
RowToAdd["SKU"] = Row["SKU"];
RowToAdd["AreaID"] = AreaID;
RowToAdd["Quantity"] = StockQuantities[0][3] = Convert.ToInt32(StockQuantities[0][3]) + 1;
RowToAdd["Condition"] = Row["Condition"];
}
else
{
RowToAdd["QuantityID"] = AreaID + "-" + Row["SKU"] + "-" + ConditionCode;
RowToAdd["SKU"] = Row["SKU"];
RowToAdd["AreaID"] = AreaID;
RowToAdd["Quantity"] = 1;
RowToAdd["Condition"] = Row["Condition"];
}
Count++;
}
else
{
RowToAdd["QuantityID"] = Row["Serial Number"];
RowToAdd["SKU"] = Row["SKU"];
AreaIDs.RowFilter = "([StorageAreaName] = '" + Row["Area"] + "')";
RowToAdd["AreaID"] = Convert.ToInt32(AreaIDs[0][0]);
RowToAdd["Quantity"] = 1;
RowToAdd["Condition"] = Row["Condition"];
Count++;
}
StockQuantitiesTable.ImportRow(RowToAdd);
MessageBox.Show(RowToAdd[0].ToString());
StockAdditions.ImportRow(RowToAdd);
}
}
private void AddRowToSQLTable(DataRow Row, string SQLTableName)
{
DataRow[] Rows = new DataRow[1];
Rows[0] = Row;
SqlConnection SQLConn = new SqlConnection(ConfigurationManager.ConnectionStrings["eCommStock.Properties.Settings.Demo_SiteConnectionString"].ConnectionString);
SQLConn.Open();
SqlDataAdapter daUpdateTable = new SqlDataAdapter("Select * From " + SQLTableName, SQLConn);
SqlCommandBuilder SQLcmdBuilder = new SqlCommandBuilder(daUpdateTable);
daUpdateTable.Update(Rows);
SQLConn.Close();
}
public void AddStock()
{
SqlConnection SQLConn = new SqlConnection(ConfigurationManager.ConnectionStrings["eCommStock.Properties.Settings.Demo_SiteConnectionString"].ConnectionString);
SQLConn.Open();
SqlDataAdapter daUpdateTable = new SqlDataAdapter("Select * From StockQuantities", SQLConn);
SqlCommandBuilder SQLcmdBuilder = new SqlCommandBuilder(daUpdateTable);
daUpdateTable.Update(StockAdditions);
SQLConn.Close();
}
It doesn't work because RowToAdd.RowState is Detached. I don't like it, but the following is a quick and dirty solution, before importing the row to StockAdditions, make sure the row is in Added state, later you can "detach" the row again.
StockQuantitiesTable.Rows.Add(RowToAdd);
StockAdditions.ImportRow(RowToAdd);
StockQuantitiesTable.Rows.Remove(RowToAdd);

Taking Value from Database and Create XML FILE VIA C#

Well I produce code which takes the values from the database and creates XML files, but I stack on how to modify my code in order to avoid the empty cells from the column VALUES, also I need to select the data from the column VALUES where the column SELECT is 1. Can you please help me with examples? Thank you in advance .
code
public DataSet produceFieldsXml(int langID, int presID)
{
SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["beta"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter(#"SELECT IsubField.ID,IsubField.SUBJECT_ID as SUBJECTID,IsubField.VALUE AS DSCR,IsubField.FIELD_TYPE_ID, PFTT.VALUE AS TITLE
FROM I_SUBJECT_FIELD IsubField, P_FIELD_TYPE_TITLE PFTT
WHERE IsubField.PRESENTATION_ID = " + presID + #"
AND IsubField.LANGUAGE_ID = " + langID + #"
AND PFTT.FIELD_TYPE_ID = IsubField.FIELD_TYPE_ID
AND PFTT.LANGUAGE_ID = " + langID + #"
ORDER BY IsubField.SUBJECT_ID", con);
DataSet ds = new DataSet();
da.Fill(ds, "FieldItem");
ds.Tables[0].Columns.Add("SEQ", typeof(Int64));
DataSet dsNew = new DataSet();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
SqlDataAdapter daII = new SqlDataAdapter(#"SELECT CATEGORY_ID FROM I_SUBJECT WHERE ID = " + Convert.ToInt32(ds.Tables[0].Rows[i]["SUBJECTID"].ToString().Trim()) + "", con);
DataSet dsa = new DataSet();
daII.Fill(dsa, "FieldItem");
dsNew.Merge(dsa);
}
DataSet dsaa = new DataSet();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
SqlDataAdapter daII = new SqlDataAdapter(#"SELECT SEQ FROM P_CATEGORY_FIELD WHERE CATEGORY_ID = " + Convert.ToInt32(dsNew.Tables[0].Rows[i]["CATEGORY_ID"].ToString().Trim()) + " AND FIELD_ID = " + Convert.ToInt32(ds.Tables[0].Rows[i]["FIELD_TYPE_ID"].ToString().Trim()) + "", con);
daII.Fill(dsaa, "FieldItem");
ds.Tables[0].Rows[i]["SEQ"] = dsaa.Tables[0].Rows[0]["SEQ"];
}
for (int i = 0; i > dsaa.Tables[0].Rows.Count; i++)
{
ds.Tables[0].Rows[i]["SEQ"] = dsaa.Tables[0].Rows[0]["SEQ"];
}
dsaa.WriteXml(Server.MapPath("~/") + "ZipFiles\\" + "new.xml");
return ds;
}
If I were you I'd really try to learn more SQL, because I'm pretty sure those three queries above can be one query given the right joins. Unfortunately we cannot help you right now, unless you show us what I_SUBJECT_FIELD, P_FIELD_TYPE_TITLE, I_SUBJECT and P_CATEGORY_FIELD look like and how they're related.
Because this is simply very bad:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
SqlDataAdapter daII = new SqlDataAdapter(#"SELECT CATEGORY_ID FROM I_SUBJECT WHERE ID = " + Convert.ToInt32(ds.Tables[0].Rows[i]["SUBJECTID"].ToString().Trim()) + "", con);
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
SqlDataAdapter daII = new SqlDataAdapter(#"SELECT SEQ FROM P_CATEGORY_FIELD WHERE CATEGORY_ID = " + Convert.ToInt32(dsNew.Tables[0].Rows[i]["CATEGORY_ID"].ToString().Trim()) + " AND FIELD_ID = " + Convert.ToInt32(ds.Tables[0].Rows[i]["FIELD_TYPE_ID"].ToString().Trim()) + "", con);
}
Those queries get executed numerous times and at most they should be executed once (bit trickier in the second case, but not impossible), and in fact they really should be part of the main query (provided the tables are set up correctly).
An even bigger headscratcher is this:
for (int i = 0; i > dsaa.Tables[0].Rows.Count; i++)
{
ds.Tables[0].Rows[i]["SEQ"] = dsaa.Tables[0].Rows[0]["SEQ"];
}
...since that is exactly the same line as in the previous for-loop.
Once you manage to create a single query it will be far easier to convert that data into XML.
Also look into encapsulating code in using statements.

Categories

Resources