Select with where clause in MySql - c#

Is it possible to select data from a table with a specific ID? I know it works for update but what is the code for the select?
Im using c# in visual studios, my goal is to display the details in readOnly textboxes.
string corp =
#"select corporateName,
corporateAddress,
corporateContact
from corporatemembership
where corporateID = CorpID.Text";

this should do it
string Command =
#"select corporateName,
corporateAddress,
corporateContact
from corporatemembership
where corporateID = #CorpID;";
using (MySqlConnection myConnection = new MySqlConnection(ConnectionString))
{
using (MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(Command, myConnection))
{
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#CorpID", CorpID.Text));
DataTable dtResult = new DataTable();
myDataAdapter.Fill(dtResult);
corporateName.Text = dtResult.Rows[0]["corporateName"];
corporateAddress.Text = dtResult.Rows[0]["corporateAddress"];
corporateContact.Text = dtResult.Rows[0]["corporateContact"];
}
}
probably you should add some error handling and handle the case that CorpID doesn't exist
UPDATE another approach
string Command =
#"select corporateName,
corporateAddress,
corporateContact
from corporatemembership
where corporateID = #CorpID;";
using (MySqlConnection mConnection = new MySqlConnection(ConnectionString))
{
mConnection.Open();
using (MySqlCommand cmd = new MySqlCommand(Command, mConnection))
{
cmd.Parameters.Add(new MySqlParameter("#CorpID", CorpID.Text));
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
corporateName.Text = (string)reader["corporateName"];
corporateAddress.Text = (string)reader["corporateAddress"];
corporateContact.Text = (string)reader["corporateContact"];
}
}
}
}

Yes, it is possible,
your sql string is OK, except last part, you will edit last part
string corp = "select corporateName, corporateAddress, corporateContact from corporatemembership where corporateID = " + "'" + CorpID.Text + "'";

Related

How to store multiple SQL data columns into different variables C#

I am trying to store sql data that I have for a voucher id and voucher amount into a variable and display it into a label on a click of a button.
protected void Button1_Click(object sender, EventArgs e)
{
string voucherId = String.Empty;
string voucherAmount = String.Empty;
string queryVoucherId = "select voucherid from ReturnForm where email = '" + Session["username"] + "';";
string queryVoucherAmount = "select voucheramount from ReturnForm where email = '" + Session["username"] + "';";
int index = 0;
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherId, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherId = reader[index].ToString();
index++;
}
}
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand cmd = new SqlCommand(queryVoucherAmount, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
voucherAmount = reader[index].ToString();
index++;
}
}
if (txtVoucher.Text == voucherId)
{
Label3.Visible = true;
Label3.Text = voucherAmount;
}
}
When I click the button its giving me an error saying that the index is out of bounds.
Building on #JSGarcia's answer - but using parameters as one ALWAYS should - you'd get this code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom WHERE Email = #email";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
// set the parameter before opening connection
// this also defines the type and length of parameter - just a guess here, might need to change this
cmd.Parameters.Add("#email", SqlDbType.VarChar, 100).Value = email;
conn.Open();
sda.Fill(dt);
conn.Close();
}
Personally, I'd rather use a data class like
public class VoucherData
{
public int Id { get; set; }
public Decimal Amount { get; set; }
}
and then get back a List<VoucherData> from your SQL query (using e.g. Dapper):
string query = $"SELECT Id, Amount FROM ReturnFrom WHERE Email = #email";
List<VoucherData> vouchers = conn.Query<VoucherData>(query).ToList();
I'd try to avoid the rather clunky and not very easy to use DataTable construct...
I strongly recommend combining your sql queries into a single one, write it into a datatable and continue your logic from there. IMHO it is much cleaner code:
string email = Session['username'];
string query = $"SELECT voucherid, voucheramount FROM ReturnFrom where Email = '{email}'";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = conn.CreateCommand())
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
conn.Open();
sda.Fill(dt);
conn.Close();
}
// Work with DataTable dt from here on
...
Well, one more big tip?
You ONLY as a general rule need a dataadaptor if you going to update the data table.
And you ONLY need a new connection object if you say not using the sql command object.
The sqlcommand object has:
a connection object - no need to create a separate one
a reader - no need to create a separate one.
Note how I did NOT create a seperate connection object, but used the one built into the command object.
And since the parameter is the SAME in both cases? Then why not re-use that too!!
So, we get this:
void TestFun2()
{
String str = "some conneciton???";
DataTable rstVouch = new DataTable();
using (SqlCommand cmdSQL =
new SqlCommand("select voucherid from ReturnForm where email = #email",
new SqlConnection(str)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = Session["username"];
cmdSQL.Connection.Open();
rstVouch.Load(cmdSQL.ExecuteReader());
// now get vouch amount
cmdSQL.CommandText = "select voucheramount from ReturnForm where email = #email";
DataTable rstVouchAmount = new DataTable();
rstVouchAmount.Load(cmdSQL.ExecuteReader());
if (rstVouch.Rows[0]["vourcherid"].ToString() == txtVoucher.Text)
{
Label3.Visible = true;
Label3.Text = rstVouchAmount.Rows[0]["voucheramount"].ToString();
}
}
}

MySql.Data.MySqlClient.MySqlException : 'There is already an open DataReader associated with this Connection which must be closed first.'

MySqlCommand Sql1 = new MySqlCommand("SELECT * FROM animal WHERE idAnimal ='" + label1.Text + "'", Connection);
MySqlDataReader dr1;
dr1 = Sql1.ExecuteReader();
while (dr1.Read())
{
String idAnimal = dr1["idAnimal"].ToString();
MySqlCommand Sql2 = new MySqlCommand("SELECT * FROM town WHERE id ='" + idAnimal + "'", Connectio);
MySqlDataReader dr2;
dr2 = Sql2.ExecuteReader();
while (dr2.Read())
{
dataGridView1.Rows.Add(dr2["number"], dr2["name"]);
}
dr2.Close();
}
dr1.Close();
Connection.Close();
The best way to solve this is with a JOIN (and fix that HUGE sql injection hole while we're at it):
string sql = "SELECT t.number, t.name FROM animal a INNER JOIN town t ON t.ID = a.idAnimal WHERE a.idAnimal= #idAnimal";
using (var cn = new MySqlConnection("connection string here"))
using (var cmd = new MySqlCommand(sql, cn))
{
cmd.Parameters.Add("#idAnimal", MySqlDbType.Int32).Value = int.Parse(label1.Text);
cn.Open();
using (var dr = cmd.ExecuteReader())
{
while(dr.Read())
{
dataGridView1.Rows.Add(dr["number"], dr["name"]);
}
dr.Close();
}
}
Additionally, you should probably look into databinding to connect those results to your grid, rather than manually adding rows. That would let you write code like this:
string sql = "SELECT t.number, t.name FROM animal a INNER JOIN town t ON t.ID = a.idAnimal WHERE a.idAnimal= #idAnimal";
using (var cn = new MySqlConnection("connection string here"))
using (var cmd = new MySqlCommand(sql, cn))
{
cmd.Parameters.Add("#idAnimal", MySqlDbType.Int32).Value = int.Parse(label1.Text);
cn.Open();
using (var dr = cmd.ExecuteReader())
{
dataGridView1.DataSource = dr;
dr.Close();
}
}
But if you really want to know how to have two DataReaders active together, you do that by having two connection objects:
using (var cn1 = new MySqlConnection("connection string here"))
using (var sql1 = new MySqlCommand("SELECT * FROM animal WHERE idAnimal = #idAnimal", cn1))
{
sql1.Parameters.Add("#idAnimal", MySqlDbType.Int32).Value = int.Parse(label1.Text);
cn1.Open();
using (var dr1 = sql1.ExecuteReader())
{
while (dr1.Read())
{
String idAnimal = dr1["idAnimal"].ToString();
using (var cn2 = new MySqlConnection("connection string here"))
using (var sql2 = new MySqlCommand("SELECT * FROM town WHERE id = #idAnimal", cn2))
{
cn2.Parameters.Add("#idAnimal", MySqlDbType.Int32).Value = int.Parse(idAnimal);
cn2.Open();
using(var dr2 = sql2.ExecuteReader())
{
while (dr2.Read())
{
dataGridView1.Rows.Add(dr2["number"], dr2["name"]);
}
dr2.Close();
}
}
}
dr1.Close();
}
}
But note how this is more than twice as much code as the JOIN + DataBinding option.
Also note that it's poor practice in ADO.Net providers to keep one database connection for re-use in your application. In addition to limiting your ability to use multiple database queries at the same time, as we see here, ADO.Net uses a feature called Connection Pooling, and re-using the same connection object interferes with this. It really is better to create a new connection object in most cases, and simply re-use the connection string.
You can't use the same "Connection" variable in two commands at the same time. Just have to create a second one if you want to open another connection inside of the Read of the first one.
You are using the same connection for the DataReader and the ExecuteNonQuery.which is not supported, according to MSDN You have to create sperate connection for each datareader

SQLite command construct WHERE clause

How to use Combobox.SelectedValue to construct WHERE clause?
conL.Open();
cmdL.Connection = conL;
cmdL.CommandText ="SELECT Id FROM dbAllServers WHERE Server_Names='" + cmb_SQLNames.SelectedValue +"'";
SQLiteDataReader r = cmdL.ExecuteReader();
while(r.Read())
{
serID = int.Parse(r[0].ToString());
MessageBox.Show("Current Selected Server ID is:..." + serID.ToString());
}
conL.Close();
An example of parameterized query, might be helpful:
string query = "SELECT Id FROM dbAllServers WHERE Server_Names=#server_name";
string serverName = cmb_SQLNames.SelectedValue;
using (SQLiteConnection connection = new SQLiteConnection(GetConnectionString()))
{
connection.Open();
using (var cmd = new SQLiteCommand(query, connection))
{
cmd.Parameters.Add(new SQLiteParameter("#server_name", serverName));
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// do your job here
}
}
}
}

ASP.NET , C# how to write this sql command

How can I write this code in asp.net c# code behinds?
Wwhat I'm trying to do is to select all rows in invoicetable with orderno that is equal to current session and deduct the inventory of my inventorytable from `invoicetable qty that matches their itemid's.
SqlCommand cmd =
new SqlCommand("UPDATE inventorytable
JOIN invoicetable ON inventorytable.ItemID = invoicetable.ItemID
SET inventorytable.inventory = inventorytable.inventory-invoice.QTY
WHERE invoicetable.No='" + Convert.ToInt32(Session["invoiceno"]) + "'"
, con);
InsertUpdateData(cmd);
Your update query is not formed correctly, and you should be using parameterized SQL. Try using something like this
var sqlQuery =
#"UPDATE inventorytable
SET inventorytable.inventory = inventorytable.inventory-invoice.QTY
FROM inventorytable
INNER JOIN invoicetable ON inventorytable.ItemID = invoicetable.ItemID
WHERE invoicetable.No=#invNo";
using (var conn = new SqlConnection(CONN_STR))
{
var sqlCmd = new SqlCommand(sqlQuery, conn);
sqlCmd.Parameters.AddWithValue("#invNo", Session["invoiceno"].ToString());
sqlCmd.ExecuteNonQuery();
}
I typed this without VS in front of me, so let me know if there are any syntax issues
var n = Session["invoiceno"] != null ? Convert.ToInt32(Session["invoiceno"]) : 0;
using (var conn = new SqlConnection(CONN_STR))
{
conn.Open();
var sql = "SELECT * FROM invoicetable WHERE orderno = #n";
var cmd = new SqlCommand(sql);
cmd.Connection = conn ;
cmd.Parameters.AddWithValue("#n", n);
using(var dr = cmd.ExecuteReader())
{
while(dr.Read())
{
//loop through DataReader
}
dr.Close();
}
}

C# use a reader in another reader solution?

I need to get some mysql data into another mysql reader request anyway to workaround that I apparently can't have 2 readers open at the same time it will all end up in a datagrid
public void DBSelectPraktikanter(object sender)
{
string Command = "SELECT * FROM forlob WHERE firmaid = N'" + firmaid + "'";
MySqlConnection sqlConnection1 = new MySqlConnection(connectionString);
MySqlCommand command = new MySqlCommand(Command, sqlConnection1);
sqlConnection1.Open();
MySqlDataReader reader = command.ExecuteReader();
var items = new List<praktikanter>();
if (reader.HasRows)
{
while (reader.Read())
{
string praktikantid = String.Format("{0}", reader["praktikantid"]);
string Command2 = "SELECT * FROM praktikanter WHERE id = N'" + praktikantid + "'";
MySqlCommand command2 = new MySqlCommand(Command, sqlConnection1);
MySqlDataReader reader2 = command.ExecuteReader();
if (reader.HasRows)
{
while (reader2.Read())
{
Praktikant = String.Format("{0}", reader["Navn"]);
}
}
string Fra = String.Format("{0}", reader["fra"]);
string Til = String.Format("{0}", reader["til"]);
items.Add(new praktikanter(Praktikant, Fra, Til));
}
}
sqlConnection1.Close();
var grid = sender as DataGrid;
grid.ItemsSource = items;
}
Instead of nesting MySqlCommands and looping the first resultset to query again the database to collect all of your data you should really use one query. Also use the using-statement to ensure that the connection gets closed even on error and use sql-parameters to avoid sql-injection issues:
var items = new List<praktikanter>();
string sql = #"SELECT p.*, f. Navn
FROM praktikanter p INNER JOIN forlob f ON p.id = f.praktikantid
WHERE f.firmaid = #firmaid";
using (var con = new MySqlConnection(connectionString))
using (var command = new MySqlCommand(sql, con))
{
command.Parameters.Add(new MySqlParameter("#firmaid", MySqlDbType.VarChar).Value = firmaid);
con.Open();
using (var rd = command.ExecuteReader())
{
while (rd.Read())
{
string praktikant = rd.GetString("Navn");
string fra = rd.GetString("Fra");
string til = rd.GetString("Til");
items.Add(new praktikanter(praktikant, fra, til));
}
}
}

Categories

Resources