SQL Server cannot build connection string to db - c#

I tried the following in SQL Server Management Studio; I can connect and run query, but not from my project
string s = "Server=LAPTOP-7J47C5JA\SQLEXPRESS;Database=Test;Trusted_Connection=True;";
string queryString = "SELECT * from tbclienti";
cn = new SQLConnection(s);
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, cn);
cn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Text = reader[0].ToString();
label1.Text = reader[1].ToString()+ " " + reader[2].ToString();
}
reader.Close();
cn.Close();

I posted here whole code what could look like. Try it now.
string s = #"Server=(local)\SQLEXPRESS;Database=Test;Integrated Security=SSPI;";
using(SqlConnection cn = new SqlConnection(s))
{
string queryString = "SELECT * from tbclienti";
try
{
cn.Open();
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, cn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Text = reader[0].ToString();
label1.Text = reader[1].ToString()+ " " + reader[2].ToString();
}
reader.Close();
}
catch(Exception ex)
{
// see if error appear
}
finally
{
cn.Close();
}
}

Related

How to execute an update query while MysqlDataReader is running

I'm using C# console app to update a table with a lot of rows based on the value of two column inside MySQL.
Below is the code that I've tried to update the table.
Is it possible to execute update during dataread while loop or do I need to use other way to accomplish this?
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
// I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}
Right now if I execute the programs, the data will not be updated and will show error
'There is already an open DataReader associated with this Connection which must be closed first.'
However if I close the connection, it will only execute and update the very first row which satisfy the if-else rule.
I think there must be a way for this to run in a loop without having me to run the program repeating times.
Can anyone suggest how should I fix the code for that?
U can define new connection object for that
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].Connection
String);
MySqlConnection con1 = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].Connection
String);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
// I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con1);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}
int currentPoints;
int shudhavePoints;
string email;
MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString);
con.Open();
MySqlCommand cmd1 = new MySqlCommand("SELECT user_email, meta_value AS 'Current Points', point FROM wp_usermeta", con);
MySqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if(rdr.HasRows)
{
while(rdr.Read())
{
email = rdr.GetString(0);
currentPoints = Int32.Parse(rdr.GetString(1));
shudhavePoints = Int32.Parse(rdr.GetString(2));
if (currentPoints>shudhavePoints)
{
//I want to update here
MySqlCommand cmd2 = new MySqlCommand("UPDATE TABLE wp_usermeta SET meta_value = #cp WHERE user_email = #email", con);
cmd2.Parameters.AddWithValue("#cp", shudhavePoints);
cmd2.Parameters.AddWithValue("#email",email);
cmd2.ExecuteNonQuery();
}
if(!rdr.read())
{
Console.WriteLine("Update query not working!!!");
}
else
{
//user_email
string usermail = Convert.ToString(user_email);
usermail = rdr[0].ToString();
Console.WriteLine("Username: {0}", usermail.ToString());
//meta_value AS 'Current Points'
string metavalue = Convert.ToString(meta_value);
metavalue = rdr[1].ToString();
Console.WriteLine("metavalue: {0}", metavalue.ToString());
//meta_value AS 'point'
string points = Convert.ToString(point);
points = rdr[2].ToString();
Console.WriteLine("point: {0}", points.ToString());
Console.ReadLine();
}
}
Console.ReadLine();
}
else
{
Console.WriteLine("I read nothing!");
Console.ReadLine();
}

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.

mysql query not working

I am trying to write a MySQL query in C# as below,I don't see any errors but neither I see the required output, the query works fine in mysqlworkbench ,am using MySql.Data.dll connection 6.9.9,what am I missing?how to debug what is wrong?
string connectionString = "server=10.xx.xxx.xx;database=databasename;uid=username;pwd=password;";
var conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = connectionString;
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = "select bb.version,bb.baat,bb.au from build bb where bb.version='x.xxx' and bb.state='COMPLETE'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0] + " -- " + rdr[1]);
Console.ReadLine();
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
try to change:
from rdr[0]
to:
rdr.GetString(0)

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

reading two MySql queries on c#

SELECT #gb FROM parameters WHERE Form_Factor =#ff I'm new with c# and it's my first programm.
I'm trying to connect mysql server and run a query.
Then, I want to take he results of the first query and run another query with them.
the first query works good, the second mysqldataread doesnt work and i cant understand why. (i'm using vs 2013).
code:
myCommand.CommandText = "SELECT GB,Form_Factor FROM devices WHERE Serial_Number = #Sn";
myCommand.Parameters.AddWithValue("#Sn", Sn);
connect.Open();
MySqlDataReader reader = myCommand.ExecuteReader();
if (reader.Read())
{
textBox2.Text = reader["GB"].ToString();
textBox3.Text = reader["Form_Factor"].ToString();
}
reader.Close();
connect.Close();
string gb = textBox2.Text;
string ff = textBox3.Text;
MySqlCommand myCommand2 = connect.CreateCommand();
myCommand2.Parameters.AddWithValue("#gb", gb);
myCommand2.Parameters.AddWithValue("#ff", ff);
myCommand2.CommandText = "SELECT #gb FROM parameters WHERE Form_Factor =#ff ";
connect.Open();
MySqlDataReader reader2 = myCommand2.ExecuteReader();
reader2.Read();
if (reader2.Read())
{
string command = reader2["#gb"].ToString();
MessageBox.Show(command);
}
if (reader2.Read() == false)
{
MessageBox.Show("read failed!");
}
reader2.Close();
connect.Close();
As I can guess #gb isn't an existing field in parameters table , thats why you aren;t getting any results in second query. Also using statement is a good practise when messing with sqlcommands:
myCommand2.CommandText = "SELECT #gb FROM parameters WHERE Form_Factor =#ff ";
myCommand2.Parameters.AddWithValue("#gb", gb);
myCommand2.Parameters.AddWithValue("#ff", ff);
using (connect)
{
connect.Open();
MySqlDataReader reader2 = myCommand2.ExecuteReader();
while (reader2.Read())
{
string command = reader2[0].ToString();
MessageBox.Show(command);
}
}
You need to read more here or here.
However, I edit your code:
myCommand.CommandText = "SELECT GB,Form_Factor FROM devices WHERE Serial_Number = #Sn";
myCommand.Parameters.AddWithValue("#Sn", Sn);
connect.Open();
MySqlDataReader reader = myCommand.ExecuteReader();
if (reader.Read())
{
textBox2.Text = reader["GB"].ToString();
textBox3.Text = reader["Form_Factor"].ToString();
}
reader.Close();
connect.Close();
string gb = textBox2.Text;
string ff = textBox3.Text;
myCOmmand.CommandText = #"SELECT * FROM parameters WHERE Form_Factor = 'Mercury';";
connect.Open();
MySqlDataReader reader2 = myCommand.ExecuteReader();
reader2.Read();
if (reader2.Read())
{
string command = reader2["columnName"].ToString();
MessageBox.Show(command);
}
if (reader2.Read() == false)
{
MessageBox.Show("read failed!");
}
reader2.Close();
connect.Close();
Make sure to edit reader2["columnName"].TOString(); -> Edit columnName to the columnName you want to get.
1st - you dont need this line:
reader2.Read();
2nd - reader2["#gb"].ToString(); is wrong put the ColumnName you need instead of "#gb"
3rd - AddWithValue make no sense in this fall, you need it only if you have a dynamic variables in your sql-query
EDIT - second part:
string gb = textBox2.Text;
string ff = textBox3.Text;
MySqlCommand myCommand2 = connect.CreateCommand();
myCommand2.CommandText = "SELECT " + gb + " FROM parameters WHERE Form_Factor = #ff;";
myCommand2.Parameters.AddWithValue("#ff", ff);
connect.Open();
MySqlDataReader reader2 = myCommand2.ExecuteReader();
if (reader2.Read())
{
string command = reader2[gb].ToString();
MessageBox.Show(command);
}
else
{
MessageBox.Show("read failed!");
}
reader2.Close();
connect.Close();

Categories

Resources