C# MySqlConnector next query in the same connection - c#

I have the following code:
string myConnection = "server=localhost;database=test;uid=test;password=test";
string query = "SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
try
{
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
MySqlCommand command = new MySqlCommand(query, myConn);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
MySqlDataReader myReader;
myReader = command.ExecuteReader();
while (myReader.Read()) {
orderNumber = myReader.GetString(1);
myReader.Close();
string queryOrder = "SELECT id_order, id_carrier FROM ps_orders WHERE id_order=28329";
MySqlCommand commandOrder = new MySqlCommand(queryOrder, myConn);
MySqlDataReader myReaderOrder;
myReaderOrder = commandOrder.ExecuteReader();
idCarrier = myReaderOrder.GetString(1);
printDocument1.Print();
}
I have a problem because the second query string queryOrder doesn't work. The query is Ok but variable "idCarrier" doesn't accept any value.

I don't believe you can attach another reader to a connection, when one is already open and processing records. You must retrieve all your records first, i.e. ToList() or Dataset, or use a secondary connection for the second reader.
To make your life easier, consider using Dapper or Linq2Db, two awesome micro-ORMs.

Try it like this:
using(var connection = new MySqlConnection("server=localhost;database=test;uid=test;password=test") {
connection.Open();
int orderNumber = 0;
using (var command = connection.CreateCommand()) {
command.CommandText = #"SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
var reader = command.ExecuteReader();
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
if(reader.Read()) {
orderNumber = Convert.ToInt32(reader.GetString(1));
}
}
using(var command = connection.CreateCommand()) {
command.CommandText = string.format(#"SELECT id_order, id_carrier FROM ps_orders WHERE id_order={0}",orderNumber);
var reader = command.ExecuteReader();
if(reader.Read()){
printDocument1.Print();
return reader.GetString(1);
}
}
}

Related

Read data from SQL Server table

I'm trying to get data from a SQL Server database and return data (all data) based on a query as follows:
public async Task<List<PersonEntity>> GetDataAsync()
{
var allUsers = new List<PersonEntity>();
SqlConnection conn = new SqlConnection("");
conn.Open();
SqlCommand cmd = new SqlCommand("Select* from <TABLE> <WHERE>", conn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var a = new PersonEntity {
LocationAreaCode = reader.GetString(0),
PersonStatusCode = reader.GetString(1),
PersonStatusDesc = reader.GetString(2)
};
allUsers.Add(a);
}
}
else
{
// no data found
}
reader.Close();
conn.Close();
return allUsers;
}
Is there a better way (in terms of performance) to read all data (values from all the columns) matching the query and return the data from this function?
You need to use ADO.net SqlDataAdapter Class
var ds = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "Select * from <table-name> where location = 'US'";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}

Return results from SQL query in a specific format [duplicate]

I'm trying to get data from a SQL Server database and return data (all data) based on a query as follows:
public async Task<List<PersonEntity>> GetDataAsync()
{
var allUsers = new List<PersonEntity>();
SqlConnection conn = new SqlConnection("");
conn.Open();
SqlCommand cmd = new SqlCommand("Select* from <TABLE> <WHERE>", conn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var a = new PersonEntity {
LocationAreaCode = reader.GetString(0),
PersonStatusCode = reader.GetString(1),
PersonStatusDesc = reader.GetString(2)
};
allUsers.Add(a);
}
}
else
{
// no data found
}
reader.Close();
conn.Close();
return allUsers;
}
Is there a better way (in terms of performance) to read all data (values from all the columns) matching the query and return the data from this function?
You need to use ADO.net SqlDataAdapter Class
var ds = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "Select * from <table-name> where location = 'US'";
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}

C# & SQL Server: executing another query while Data Reader is opened

I am intending to perform a call to ExecuteNonQuery() while the SqlDataReader is opened.
Code:
string commandString = "" //command string
using (SqlDataReader reader = cmd2.ExecuteReader())
{
while (reader.Read())
{
string temp = Convert.ToString(reader["RequestID"]);
string date;
using (SqlCommand cmd3 = new SqlCommand(commandString, con))
{
date = Convert.ToString(cmd3.ExecuteScalar());
}
}
}
I tried executing this but I got the error:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
There is already an open DataReader associated with this Command which must be closed first.
I have the MultipleActiveResultSets set to True in the connection string. May I know if it is possible to do it?
While MARS should work, it's usually not the best choice. Simply load the results of the first query into a DataTable and iterate the rows.
var dt = new DataTable();
using (SqlDataReader reader = cmd2.ExecuteReader())
{
dt.Load(reader);
}
foreach (DataRow row in dt.Rows)
{
string temp = Convert.ToString(row["RequestID"]);
string date;
SqlCommand cmd3 = new SqlCommand(commandString, con)
date = Convert.ToString(cmd3.ExecuteScalar());
}
You need to add MultipleActiveResultSets in your connection string, though you already added. Try below code that's executed successfully,
string conStr = "Data Source=DB_SERVER;Initial Catalog=DB_NAME;User Id=userId; Password=password;MultipleActiveResultSets=True";
using (SqlConnection con = new SqlConnection(conStr)) {
try {
con.Open();
string commandText = #"Select Id from Table1";
string commandText1 = #"Select CreatedDate FROM Table2 Where table1_Id = #table1_Id";
SqlCommand sqlCommand = new SqlCommand(commandText, con);
var dataReader = sqlCommand.ExecuteReader();
string date;
while (dataReader.Read()) {
var vId = dataReader["Id"].ToString();
var sqlCommand1 = new SqlCommand(commandText1, con);
sqlCommand1.Parameters.AddWithValue("#table1_Id", vId);
date= sqlCommand1.ExecuteScalar().ToString();
}
con.Close();
} catch (Exception ex) {
//Handle Exception
}
}

Autocomplete combobox with SQL Server database

When filling a combobox with data in database, the first row in database was missing.
con = new SqlConnection(cs.connetionString);
con.Open();
Sql = "SELECT * FROM ItemRate";
command = new SqlCommand(Sql, con);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
while (reader.Read())
{
string cat = reader["RateOfInt"].ToString();
comboBox4.Items.Add(cat);
}
Calling reader.Read() advances one row, so the first time you call it before the while loop it already lands on the first row, but then you call it again in the while condition, so it advances to the second row, just remove the call before the condition.
con = new SqlConnection(cs.connetionString);
con.Open();
Sql = "SELECT * FROM ItemRate";
command = new SqlCommand(Sql, con);
SqlDataReader reader = command.ExecuteReader();
// remove this line
// reader.Read();
while (reader.Read())
{
string cat = reader["RateOfInt"].ToString();
comboBox4.Items.Add(cat);
}
Edit: Here is the example from the Docs
con = new SqlConnection(cs.connetionString);
con.Open();
Sql = "SELECT * FROM ItemRate";
command = new SqlCommand(Sql, con);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string cat = reader["RateOfInt"].ToString();
comboBox4.Items.Add(cat);
}

How to get list of all database from sql server in a combobox using c#.net

I am entering the source name userid and password through the textbox and want the database list should be listed on the combo box so that all the four options sourcename, userid, password and databasename can be selected by the user to perform the connectivity
The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity
private void frmConfig_Load(object sender, EventArgs e)
{
try
{
string Conn = "server=servername;User Id=userid;" + "pwd=******;";
con = new SqlConnection(Conn);
con.Open();
da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cbSrc.Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am trying to do this but it is not generating any data
sys.databases
SELECT name
FROM sys.databases;
Edit:
I recommend using IDataReader, returning a List and caching the results. You can simply bind your drop down to the results and retrieve the same list from cache when needed.
public List<string> GetDatabaseList()
{
List<string> list = new List<string>();
// Open connection to the database
string conString = "server=xeon;uid=sa;pwd=manager; database=northwind";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
First add following assemblies:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
from
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\
and then use below code:
var server = new Microsoft.SqlServer.Management.Smo.Server("Server name");
foreach (Database db in server.Databases) {
cboDBs.Items.Add(db.Name);
}
you can use on of the following queries:
EXEC sp_databases
SELECT * FROM sys.databases
Serge
Simply using GetSchema method:
using (SqlConnection connection = GetConnection())
{
connection.Open();
DataTable dtDatabases = connection.GetSchema("databases");
//Get database name using dtDatabases["database_name"]
}
using (var connection = new System.Data.SqlClient.SqlConnection("ConnectionString"))
{
connection.Open();
var command = new System.Data.SqlClient.SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT name FROM master.sys.databases";
var adapter = new System.Data.SqlClient.SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
DataTable dtDatabases = dataset.Tables[0];
}
How to get list of all database from sql server in a combobox using c# asp.net windows application
try
{
string Conn = "server=.;User Id=sa;" + "pwd=passs;";
SqlConnection con = new SqlConnection(Conn);
con.Open();
SqlCommand cmd = new SqlCommand();
// da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cmd = new SqlCommand("SELECT name FROM sys.databases", con);
// comboBox1.Items.Add(cmd);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//comboBox2.Items.Add(dr[0]);
comboBox1.Items.Add(dr[0]);
}
}
// .Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Try this:
SqlConnection con = new SqlConnection(YourConnectionString);
SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbSrc.Items.Add(dr[0].ToString());
}
con.Close();
or this:
DataSet ds = new DataSet();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT name from sys.databases", YourConnectionString);
sqlda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbSrc.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
public static List<string> GetAllDatabaseNamesByServerName(string ServerName, [Optional] string UserID, [Optional] string Password)
{
List<string> lstDatabaseNames = null;
try
{
lstDatabaseNames = new List<string>();
//string servername = System.Environment.MachineName;
string newConnString = string.Format("Data Source={0};", ServerName);
if (UserID == null)
{
newConnString += "Integrated Security = True;";
}
else
{
newConnString += string.Format("User Id ={0}; Password={1};", UserID, Password);
}
SqlConnection con = new SqlConnection(newConnString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT name FROM master.sys.databases", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
lstDatabaseNames.Add(row[0].ToString());
}
con.Close();
return lstDatabaseNames;
}
finally
{
}
}

Categories