Execute multiple mysql query in C# - c#

I am trying to execute two mysql query in my C# program but I got the result of the first query only while I want to retrieveall the sql query results.
How to execute the two query and retrieve all results and print them in the console because the reader print the content of the first one only.
string wl_query = "select * from `tab1`";
MySqlCommand cmd = new MySqlCommand(wl_query, db.connectdb);
MySqlDataReader reader = cmd.ExecuteReader();
string server;
string username;
string password;
string database;
string wl_config_id;
string server_ip;
string server_username;
string user_password;
while (reader.Read())
{
server = reader["server"].ToString();
Console.WriteLine(server);
username = reader["username"].ToString();
Console.WriteLine(username);
password = reader["password"].ToString();
Console.WriteLine(password);
database = reader["database"].ToString();
Console.WriteLine(database);
wl_config_id = reader["wl_id"].ToString();
string config_query = "SELECT * FROM `tab_config` where id=" + wl_config_id + ";";
MySqlCommand config_cmd = new MySqlCommand(config_query, db.connectdb);
while (reader.Read())
{
server_ip = reader["server_ip"].ToString();
Console.WriteLine(server_ip);
server_username = reader["server_username"].ToString();
Console.WriteLine(server_username);
user_password = reader["password"].ToString();
Console.WriteLine(user_password);
}
}

Related

Can't seem to get a DataReader to work in C# / SQL Server

I have this code:
string strConnect = "Server=DESKTOP-2Q73COU\\SQLEXPRESS;Database=LoginApp;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection(strConnect);
conn.Open();
MessageBox.Show("Connected to SSMS.");
string loadMainInfo = "SELECT * FROM Main_Information WHERE Username = " + Globals.username;
SqlCommand cmd = new SqlCommand(loadMainInfo, conn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
lblStanding.Text = (dr["Standing"].ToString());
lblName.Text = (dr["First Name"].ToString()) + " " + (dr["Last Name"].ToString());
lblTotalHours.Text = (dr["Total_hours"].ToString());
lblType.Text = (dr["Degree_type"].ToString());
lblDegree.Text = (dr["Degree"].ToString());
lblCurrentHours.Text = (dr["Current_hours"].ToString());
}
Specifically this line:
string loadMainInfo = "SELECT * FROM Main_Information WHERE Username = " + Globals.username;
If I replace the end of that line with:
Username = testuser"
The code will work fine and all labels below will be populated with the corresponding info from the tables where Username = testuser. However, if the user logs in with their username and the code is using the original line, I get this error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
Any help?
use a SqlParameter to do it as :
string loadMainInfo = "SELECT * FROM Main_Information WHERE Username = #paramName"';
SqlParameter param1 = new SqlParameter () ;
param1.ParameterName="#paramName";
param1.SqlDbType= SqlDbType.Varchar;
param1.Value= Globals.username;
cmd.Parameters.Add(param1);
You have make a wrong query, add the quote as this
string loadMainInfo = "SELECT * FROM Main_Information WHERE Username = '" + Globals.username + "'";
You could use String.Format
string loadMainInfo = String.Format(“SELECT * FROM Main_Information WHERE Username = {0}" ,Globals.username);
It looks like Globals.username may not have a value when you're referencing it for your query string, as the SQL error you're getting occurs when there is nothing following the = in the query.
I'd suggest using the debugger to look at the value of loadMainInfo just after its been set (or otherwise add the line MessageBox.Show(loadMainInfo); below).
Does the query string include the username value you expect?

Exception: Invalid attempt to Read when reader is closed

I am trying to update my database while reading data from it, but the reader gets closed and it throws the exception that it can''t read wen reader is closed. Is the update.ExecuteNonQuery() closing the reader method?
If i get rid of linescon.Close(); con.Open(); i get There is already an open DataReader associated with this Connection which must be closed first.
So how can i update my database records while keep the reading opened?
{
public class MySqlReadUpdate
{
public int Id { get; set; }
public string Notes { get; set; }
}
static void Main()
{
List<MySqlReadUpdate> dbData = new List<MySqlReadUpdate>();
var config = "server=localhost;user id=root; database=restaurants; pooling=false;SslMode=none;Pooling=True";
MySqlConnection con = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT id, notes FROM customers";
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
MySqlReadUpdate newMySqlReadUpdate = new MySqlReadUpdate();
newMySqlReadUpdate.Id = (int)reader["id"];
newMySqlReadUpdate.Notes = (string)reader["notes"];
string note = newMySqlReadUpdate.Notes;
var notesplit = note.Split(' ', '\n')[1];
dbData.Add(newMySqlReadUpdate);
Console.WriteLine(newMySqlReadUpdate.Id);
Console.WriteLine(newMySqlReadUpdate.Notes);
Console.WriteLine(note);
Console.WriteLine(notesplit);
con.Close();
con.Open();
string query2 = "UPDATE customers SET notes='" + notesplit + "' WHERE id='" + newMySqlReadUpdate.Id + "';";
MySqlCommand update = new MySqlCommand(query2, con);
update.ExecuteNonQuery();
}
con.Close();
Console.WriteLine("Finished!");
Console.Read();
}
}
}
You cannot close a connection like you are, because the data reader depends on it. Once you call con.Close you break it. That's why you see an exception the next time it gets to reader.Read().
What you want is to add MultipleActiveResultSets=True in the configuration string; however, as we discussed in the comments it's apparently still not supported in MySQL. Therefore, the answer is two connection instances.
List<MySqlReadUpdate> dbData = new List<MySqlReadUpdate>();
var config = "server=localhost;user id=root;database=restaurants;pooling=false;SslMode=none";
MySqlConnection con = new MySqlConnection(config);
MySqlConnection cmdCon = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT id, notes FROM customers";
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
cmdCon.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
MySqlReadUpdate newMySqlReadUpdate = new MySqlReadUpdate();
newMySqlReadUpdate.Id = (int)reader["id"];
newMySqlReadUpdate.Notes = (string)reader["notes"];
string note = newMySqlReadUpdate.Notes;
var notesplit = note.Split(' ', '\n')[1];
dbData.Add(newMySqlReadUpdate);
Console.WriteLine(newMySqlReadUpdate.Id);
Console.WriteLine(newMySqlReadUpdate.Notes);
Console.WriteLine(note);
Console.WriteLine(notesplit);
string query2 = "UPDATE customers SET notes='" + notesplit + "' WHERE id='" + newMySqlReadUpdate.Id + "';";
MySqlCommand update = new MySqlCommand(query2, cmdCon);
update.ExecuteNonQuery();
}
con.Close();
cmdCon.Close();
Console.WriteLine("Finished!");
Console.Read();
I would recommend that you also modify your code to use using statements or wrap things in try-finally blocks.

Issue in the Login code in C#

I have modified my previously written code but still not able to find the flaw....
I am trying to check Login using column names of DB as parameters in the code.
The If statement that I have provided does not seem to be working as the code always displays an Unsuccessful Login whereas the parameters are able to return the Database record on the console..(as shown in the link below).
Yet the control does not enter the if statement...
This is the code::
private void button1_Click(object sender, EventArgs e)
{
String s1 = textBox1.Text;
String s2 = textBox2.Text;
SqlConnection cnn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
String sql = ("select Userid,Password from reg where Userid='" + s1 + "' and Password='" + s2 + "' ");
cnn.Open();
String userid="";
String password="";
SqlCommand cmd = new SqlCommand(sql,cnn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while(reader.Read())
{
userid = reader.GetString(0);
password = reader.GetString(1);
Console.WriteLine(userid);
Console.WriteLine(password);
}
if((s1.Equals(userid)) && (s2.Equals(password)))
{
MessageBox.Show("LOGIN SUCCESSFULLY DONE>>");
}
else
{
MessageBox.Show("LOGIN UNSUCCESSFUL ....");
}
}
[Database EntryOutput
You need to use AND in the WHERE clause instead of a comma:
String sql=("select userid,password from reg where Userid='"+s1+"' and Password='"+s2+"' ")
^^^
Then you need to execute the query:
string userid, password;
using(var cmd = new SqlCommand(sql,cnn))
{
cnn.Open();
using (var reader = cmd.ExecuteReader())
{
reader.Read();
userid = reader.GetString(0);
password = reader.GetString(1);
}
}
THEN you use the values in the if statement:
if ((s1.Equals(userid)) && (s2.Equals(password)))
The code I wrote actually had no flaws in it. The problem here was run time during the entry of the data.Trailing white spaces are also being considered because of which the strings are not able to be matched successfully.Hence to resolve the problem I have used the trim() function.
This is the change I made -
String s1 = textBox1.Text.Trim();
String s2 = textBox2.Text.Trim();
//And further in the while loop
userid = reader.GetString(0).Trim();
password = reader.GetString(1).Trim();

MySql UPDATE error. c#

ionline - class, string myname
private static void SetOnlineStatus(PacketHeader header, Connection connection, ionline message)
{
Console.WriteLine("Check online: " + message.myname);
MySqlCommand mycmd = new MySqlCommand();
mycmd.CommandText = "SELECT * FROM users WHERE username = ?user";
mycmd.Connection = mconnection;
mycmd.Parameters.AddWithValue("user", message.myname);
MySqlDataReader Reader = mycmd.ExecuteReader();
while (Reader.Read())
{
Console.WriteLine("Check online: " + message.myname+" "+GetDBString("username",Reader));
MySqlCommand mycmd2 = new MySqlCommand();
mycmd2.CommandText = "UPDATE users SET online = 0 WHERE userid = #user2";
mycmd2.Parameters.AddWithValue("#user2", Reader.GetInt32("userid"));
mycmd2.Connection = mconnection;
Console.WriteLine(mycmd2.ExecuteNonQuery().ToString());
}
}
Mysql request "mycmd2" isn't executed . What in my query not the correct?
While a DataReader is open its connection is busy serving the reader.
The connection cannot be used to make other operations on the database.
You should get an exception though.
If your first query returns zero or one row, then you could simplify your code using the ExecuteScalar method and removing the need to use a MySqlDataReader
Console.WriteLine("Check online: " + message.myname);
MySqlCommand mycmd = new MySqlCommand();
mycmd.CommandText = "SELECT userid FROM users WHERE username = ?user";
mycmd.Connection = mconnection;
mycmd.Parameters.AddWithValue("user", message.myname);
object result = mycmd.ExecuteScalar();
if(result != null)
{
int userID = Convert.ToInt32(result);
MySqlCommand mycmd2 = new MySqlCommand();
mycmd2.CommandText = "UPDATE users SET online = 0 WHERE userid = #user2";
mycmd2.Parameters.AddWithValue("#user2", userID);
mycmd2.Connection = mconnection;
mycmd2.ExecuteNonQuery();
}

Error "Specified cast is not valid" when pulling from spreadsheet in C#

I have a C# program that is supposed to pull data from a small, four-column spreadsheet (.xlsx). It reads the first column fine, however when it gets to the second I get the following error:
"Specified cast is not valid"
I've checked and re-checked the format of the cells, and there is no difference between the first column, which reads just fine, and the second. Below are the values for the first row in the spreadsheet. Each value represents one separate column.
121220 330004 Dual 02/22/2012
And here is the code that I am using. the Id variable loads just fine, it is the courseCode which is causing the problem.
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=C:\Projects\sym_AgentServices_INT\Book1.xlsx;"
+ "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string queryString = "SELECT * FROM [CE$]";
try
{
OleDbDataReader reader;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
string Id = "";
string courseCode = "";
string partner = "";
string effectiveDate = "";
string expirationDate = "";
Id = reader.GetString(0);
courseCode = reader.GetString(1);
partner = reader.GetString(2);
effectiveDate = reader.GetString(3);
expirationDate = reader.GetString(4);
}
}
}
EDIT
I've analyzed the reader object at runtime and found the following: by expanding base a number of times and opening up the _bindings property of System.Data.OleDb.OleDbDataReader I found that there was only one entry in there ("0"). However, if I open 0 up, then expand the _columnBindings property I find the values 0 - 4.
Could my syntax be incorrect when extracting data from the reader ("reader.GetString(x)")?
FINAL EDIT
Instead of using .GetString(x) I would highly recommend simply using reader[x].ToString(). This solved the problem.
When I use reader[n].ToString(), the error goes away for me:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=d:\temp\Book1.xlsx; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string queryString = "SELECT * FROM [CE$]";
OleDbDataReader reader;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
DataSet ds = new DataSet("Book1");
IDataAdapter adapter = new OleDbDataAdapter(queryString, connection);
adapter.Fill(ds);
reader = command.ExecuteReader();
while (reader.Read())
{
string Id = "";
string courseCode = "";
string partner = "";
string effectiveDate = "";
string expirationDate = "";
Id = reader[0].ToString();
courseCode = reader[1].ToString();
partner = reader[2].ToString();
effectiveDate = reader[3].ToString();
expirationDate = reader[4].ToString();
//Id = reader.GetString(0);
//courseCode = reader.GetString(1);
//partner = reader.GetString(2);
//effectiveDate = reader.GetString(3);
//expirationDate = reader.GetString(4);
}
}
Here's my test data set...
ID Course Code Partner Effective Date Expiration Date
100 5 MS 10/3/2012 10/3/2013
200 21-400 Oracle 10/3/2012 10/3/2013
300 Goog 10/3/2012 10/3/2013

Categories

Resources