This Code is establishing a Mysql Connection.
namespace TrialConnection
{
public class DataConnection
{
public static string database = "";
public static string databasename = "";
public static string user = "";
public static string password = "";
public static string charset = "latin1";
string connString = "";
public DataLayer(ref MySqlCommand newconnection)
{
connString = "On server = " + database + "; Databasename = " + databasename + "; User = "
+ user + "; Pass = " + password + "; Locale = " + charset;
newconnection = new MySqlCommand();
}
public bool modifyData(ref MySqlCommand newconnection, Alter_Procedures myQuery)
{
MySqlConnection myconnection = new MySqlConnection(connString);
newconnection.Connection = myconnection;
newconnection.CommandText = modifyQuery.ToString();
newconnection.CommandType = CommandType.StoredProcedure;
MySqlTransaction mytransaction = null;
try
{
myconnection.Open();
mytransaction = myconnection.BeginTransaction();
newconnection.Transaction = mytransaction;
newconnection.ExecuteNonQuery();
mytransaction.Commit();
mytransaction.Dispose();
myconnection.Close();
myconnection.Dispose();
}catch(Exception e){}
}
public bool getData(ref MySqlCommand newconnection, Retrieve_Procedures allproc, ref MySqlDataReader myReader)
{
MySqlConnection myConnection = new MySqlConnection(connString);
newconnection.Connection = myConnection;
newconnection.CommandType = CommandType.StoredProcedure;
newconnection.CommandText = allproc.ToString();
myConnection.Open();
myReader = newconnection.ExecuteReader();
}
}
}
Whenever I try to connect and there is no stored procedure yet in the database, it is not always taking the values for my database, databasename, user, Password and charset.
I tried to debug it and found something, however I am not sure whether I found everything.
I am very thankful for help.
Related
Currently I'm working on a project that generates files....().
Everything seems to work well. I can connect to the database and my methods of reading and writing are working, too, but I can't find the table. I have an error:
$exception {"Invalid object name 'T_SAL'."} System.Data.SqlClient.SqlException
I don't know if the problem is with my connection string or something else!
Is there anyone that can help me with this, please?
My methods' code:
//SQL connection Methods**
public static SqlConnection OpenSql(bool Authentification, string SQL_LOGIN, string SQL_PASSWORD, string SQL_SERVER, string BASE_CONSOLE)
{
try
{
SqlConnection conn = new SqlConnection();
String Securité;
if (Authentification)
{
Securité = "Integrated Security = true";
}
else
{Securité = "User Id =" + SQL_LOGIN + ";" + "Password =" + SQL_PASSWORD;}
conn.ConnectionString = "Data Source=" + SQL_SERVER + ";Initial Catalog=" + BASE_CONSOLE + ";" + Securité + ";";
conn.Open();
return conn;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return null;
}
// Generation :
private void Gen_f_Click(object sender, EventArgs e)
{
SqlConnection conn = Methodes.OpenSql(Authentification.Checked, SQL_SERVER.Text, BASE_CONSOLE.Text, SQL_LOGIN.Text, SQL_PASSWORD.Text );
if (conn == null)
{
MessageBox.Show("Connexion impossible");
return;
}
try
{
//traitement du fichier des salaeiés
var lines = Methodes.lecture(fp_text.Text);
foreach (var ligne in lines)
{
string[] cols = ligne.Split(char.Parse(";"));
string Matricule = cols[0];
if (Matricule != "" && MatriculeExiste(conn, Matricule) == false)
{
string ligneSorties = "";
ligneSorties = ligneSorties + cols[0] + ";";
Methodes.Ecriture(ligneSorties, "fp_sorties.'Text'", true);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private bool MatriculeExiste(SqlConnection conn, string Matricule)
{
SqlCommand command = new SqlCommand("SELECT MatriculeSalarie FROM [T_SAL] WHERE MatriculeSalarie='" + Matricule + "'", conn);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
return true;
}
else
{
return false;
}
}
}
The issue seems to be in the order of parameters that you pass to OpenSql method:
public static SqlConnection OpenSql(bool Authentification, string SQL_LOGIN, string SQL_PASSWORD, string SQL_SERVER, string BASE_CONSOLE)
This is how you call it:
SqlConnection conn = Methodes.OpenSql(Authentification.Checked, SQL_SERVER.Text, BASE_CONSOLE.Text, SQL_LOGIN.Text, SQL_PASSWORD.Text );
There is definitely some mismatch with the order of parameters, your declaration expects SQL_Login, SQL_PASSWORD, SQL_SERVER, BASE_CONSOLE and you are passing SQL_SERVER, BASE_CONSOLE, SQL_LOGIN, SQL_PASSWORD
So if you use Windows Authentication, it would work, because you are not passing login and password, but instead of correct Database Name you are passing password, so your user ends up into Master db, which does not contain required table.
My connection string:
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=\\reso-fs-2\allusers\Student_Home\20350657\Documents\clicker.accdb;" +
#"Jet OLEDB:Database Password=" + "password" + ";";
OleDbConnection con = new OleDbConnection(connection);
So I have this query in C# OleDb:
string query = "SELECT stats_best FROM Users WHERE username="+GameForm.username;
I want to fetch the value from 'stats_best' and save it into a string.
I have already set-up the connection and all that. I just need to return a value from the query.
How can I do that?
Please Read this article, but anyway, you can use this
public string Test(string userName, string connectionString, out string dbErrorMessage)
{
string result = null;
dbErrorMessage = null;
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.Parameters.Add(new SqlParameter("#UserName", userName));
cmd.CommandText = "SELECT stats_best FROM Users WHERE username= #UserName";
result = cmd.ExecuteScalar().ToString();
}
}
catch (Exception ex)
{
dbErrorMessage = ex.Message;
}
return result;
}
and the usage of method:
string dbErrorMessage = null;
Test(GameForm.username, connectionString, out dbErrorMessage);
I have a log viewing application that writes log statements to a database and then sends them from the database to the log viewer GUI. I want to be able to open more than one instance of the log viewer but when I do it will be creating a database with the same name as the previous instance of the viewer. I've tried creating a database with a different name if one has already been created but that doesn't seem to work. Any suggestions? Here's the code for creating/accessing/destroying databases:
public class Database
{
public bool hasAdminPriv
{
get;
set;
}
public bool hasBeenCreated
{
get;
set;
}
public Database()
{
hasAdminPriv = true;
//Construction checks to see if user has Admin priveleges
bool isElevated;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (!isElevated)
hasAdminPriv = false;
}
//returns true if the database creation was successful
public bool CreateDatabase()//creates a database dynamically by making a query request to the server
{
String str;
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=Master;Integrated Security=True");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseData.mdf', " +
"SIZE = 30MB, MAXSIZE = 10GB, FILEGROWTH = 20%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseLog.ldf', " +
"SIZE = 10MB, " +
"MAXSIZE = 1GB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
int done = 0;
while (done < 10)
{
String str2 = "CREATE DATABASE" + done + " MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseData.mdf', " +
"SIZE = 30MB, MAXSIZE = 10GB, FILEGROWTH = 20%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseLog.ldf', " +
"SIZE = 10MB, " +
"MAXSIZE = 1GB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand2 = new SqlCommand(str2, myConn);
try{
myCommand2.ExecuteNonQuery();
}
catch{
++done;
}
myConn.Close();
hasBeenCreated = true;
return true;
}
return false;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
hasBeenCreated = true;
return true;
}
//Creates the table in the database by a query request
//a return value of true means Database was created succesfully
public bool CreateTable()
{
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=MyDatabase;Integrated Security=True");
string createString = "CREATE TABLE storage (ID INT NOT NULL, Level varchar(255) , LevelInt INT, DateTime varchar(255),Counter smallint,Device varchar(255), Source varchar(255), Description varchar(255),PRIMARY KEY (ID))"; //YOUR SQL COMMAND TO CREATE A TABLE
SqlCommand create = new SqlCommand(createString, myConn);
myConn.Open();
create.ExecuteNonQuery();
myConn.Close();
return true;
}
//Add the element's values to the database/table to later recall/reorder
public bool addElement(LogParse log,int num)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into storage(ID, Level, LevelInt, DateTime, Counter, Device, Source, Description) values(" + num + ",#Level, #LevelInt, #DataTimeItem,#counterItem,#deviceItem,#sourceItem,#descItem)", con);
cmd.Parameters.AddWithValue("#Level", log.Level);
cmd.Parameters.AddWithValue("#LevelInt", log.LevelInt);
cmd.Parameters.AddWithValue("#DataTimeItem", log.TimeStamp);
cmd.Parameters.AddWithValue("#counterItem", log.SequentialNumber);
cmd.Parameters.AddWithValue("#deviceItem", log.Device);
cmd.Parameters.AddWithValue("#sourceItem", log.Source);
cmd.Parameters.AddWithValue("#descItem", log.Description);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
return false;
}
return true;
}
//outputs a string array with all the values in the database
public LogParse[] readValue(int start, int end)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
con.Open();
LogParse[] s = new LogParse[end - start];
try
{
using (var oCommand = new SqlCommand("SELECT * From storage WHERE ID BETWEEN #Start AND #End", con))
{
oCommand.Parameters.AddWithValue("#Start", start);
oCommand.Parameters.AddWithValue("#End", end);
using (var oReader = oCommand.ExecuteReader())
{
int i = 0;
while (oReader.Read() && i < end-start)
{
//s[i] = oReader.GetString(1) + oReader.GetString(2) + oReader.GetString(3);
String Level = oReader.GetString(1);
Int32 LevelInt = oReader.GetInt32(2);
String Datetime = oReader.GetString(3);
Int16 SequentialNumber = (Int16)oReader.GetValue(4);
String Device = oReader.GetString(5);
String Source = oReader.GetString(6);
String Description = oReader.GetString(7);
s[i] = new LogParse();
s[i].Level = Level;
s[i].LevelInt = LevelInt;
s[i].TimeStamp = DateTime.Parse(Datetime);
s[i].SequentialNumber = SequentialNumber;
s[i].Device = Device;
s[i].Description = Description;
s[i].Source = Source;
++i;
}
}
}
}
catch
{
}
con.Close();
return s;
}
//Deletes the database by a query statement
//a return value of true means the delete was succesful
public static bool deleteDatabase()
{
String str;
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=Master;Integrated Security=True");
str = #"ALTER DATABASE MyDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE;DROP DATABASE [MyDatabase]";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
return false;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
return true;
}
}
DON'T create another database, or table, it's evil. Just add Instance ID into table storage. And when writing new logs just add instance ID, same goes when reading from DB, put instance ID into where clause.
Another issue is to pick good Instance ID, your scenario is not very clear to me, but if you want every new application instance to have separate data, just create new GUID and use it as Instance ID.
For example you can have static property InstanceID in your Database class, and your class could look something like this :
public class Database
{
public static Guid InstanceID = new Guid();
//Add the element's values to the database/table to later recall/reorder
public bool addElement(LogParse log,int num)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into storage(ID, InstanceID, Level, LevelInt, DateTime, Counter, Device, Source, Description) values(" + num + ",#Level, #LevelInt, #DataTimeItem,#counterItem,#deviceItem,#sourceItem,#descItem)", con);
// writing InstanceID
cmd.Parameters.AddWithValue("#InstanceID", Database.InstanceID);
cmd.Parameters.AddWithValue("#Level", log.Level);
cmd.Parameters.AddWithValue("#LevelInt", log.LevelInt);
cmd.Parameters.AddWithValue("#DataTimeItem", log.TimeStamp);
cmd.Parameters.AddWithValue("#counterItem", log.SequentialNumber);
cmd.Parameters.AddWithValue("#deviceItem", log.Device);
cmd.Parameters.AddWithValue("#sourceItem", log.Source);
cmd.Parameters.AddWithValue("#descItem", log.Description);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
return false;
}
return true;
}
//outputs a string array with all the values in the database
public LogParse[] readValue(int start, int end)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
con.Open();
LogParse[] s = new LogParse[end - start];
try
{
// select with InstanceID
using (var oCommand = new SqlCommand("SELECT * From storage WHERE InstanceID = #InsID ID BETWEEN #Start AND #End", con))
{
oCommand.Parameters.AddWithValue("#Start", start);
oCommand.Parameters.AddWithValue("#End", end);
oCommand.Parameters.AddWithValue("#InsID", Database.InstanceID);
using (var oReader = oCommand.ExecuteReader())
{
int i = 0;
while (oReader.Read() && i < end-start)
{
//s[i] = oReader.GetString(1) + oReader.GetString(2) + oReader.GetString(3);
String Level = oReader.GetString(1);
Int32 LevelInt = oReader.GetInt32(2);
String Datetime = oReader.GetString(3);
Int16 SequentialNumber = (Int16)oReader.GetValue(4);
String Device = oReader.GetString(5);
String Source = oReader.GetString(6);
String Description = oReader.GetString(7);
s[i] = new LogParse();
s[i].Level = Level;
s[i].LevelInt = LevelInt;
s[i].TimeStamp = DateTime.Parse(Datetime);
s[i].SequentialNumber = SequentialNumber;
s[i].Device = Device;
s[i].Description = Description;
s[i].Source = Source;
++i;
}
}
}
}
catch
{
}
con.Close();
return s;
}
}
btw. DON'T swallow exceptions ! I leave your code the same but please don't do that, it's also evil, another thing is if there is a exception in your addElement method your connection will not be closed, use Using statement.
that doesn't sound safe at all, maybe one database with several user tables to store the logfiles for each user, but this just doesn't sound right to me.
otherwise a variable that is assigned randomly when the application is started in place of the database name when it is created.
but if you do something wrong there are going to be a lot of databases out there, but it looks like you have figured out sizing and some other things to keep them from overpowering the server machine.
Additional Information from Comment
if you are going to use tables on the Database(which I think is what you really need) then create the database separate and then create randomly named tables inside your application every time it is opened, you may want to have another table that would keep track of the the tables and the times they were opened as well, perhaps even what user opened them and such things like that
Is it possible to generate the database creation scripts for a SQL server database from .NET?
I am using C# and I would like to create some sort of an installer project for my application
on which I can select an existing database, generate the creation scripts and run them on another SQL server instance.
Yes, it is possible.
It's easy to do this with SMO, see Transfer class for scripting operations and Database class for database operations (create, drop, etc). Usage looks like this:
private StringCollection GetTransferScript(Database database)
{
var transfer = new Transfer(database);
transfer.CopyAllObjects = true;
transfer.CopyAllSynonyms = true;
transfer.CopyData = false;
// additional options
transfer.Options.WithDependencies = true;
transfer.Options.DriAll = true;
transfer.Options.Triggers = true;
transfer.Options.Indexes = true;
transfer.Options.SchemaQualifyForeignKeysReferences = true;
transfer.Options.ExtendedProperties = true;
transfer.Options.IncludeDatabaseRoleMemberships = true;
transfer.Options.Permissions = true;
transfer.PreserveDbo = true;
// generates script
return transfer.ScriptTransfer();
}
if you want to create database dynamically with c# code then here is the code:
you can do it like this also:
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
SqlConnection con = new SqlConnection();
con.ConnectionString = Connectionstring;
bool resultdbexistencx = CCMMUtility.CheckDatabaseExists(con, txt_DbName.Text);
if (!resultdbexistencx)
{
// if not exists create it check the user name for sub-admin avialibe or not.
if (txt_DbName.Text.Trim() == string.Empty) return;
string strDbCreate;
strDbCreate = "CREATE DATABASE " + txt_DbName.Text + " ON PRIMARY " +
"(NAME = " + txt_DbName.Text + "_Data, " +
"FILENAME = 'D:\\" + txt_DbName.Text + "Data.mdf', " +
"SIZE = 4MB, MAXSIZE = 10GB, FILEGROWTH = 100%) " +
"LOG ON (NAME = " + txt_DbName.Text + "_Log, " +
"FILENAME = 'D:\\" + txt_DbName.Text + ".ldf', " +
"SIZE = 4MB, " +
"MAXSIZE = 10GB, " +
"FILEGROWTH = 100%)";
SqlConnection sqlconn = new SqlConnection(Connectionstring);
SqlCommand cmd = new SqlCommand(strDbCreate, sqlconn);
try
{
sqlconn.Open();
sqlconn.ChangeDatabase("master");
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Int32 dbRollbackResult = RollBackTheWholetransaction(txt_DbName.Text.Trim(), Convert.ToInt32(HospitalResult));
if (dbRollbackResult == 1)
{
Response.Write(ex.Message);
lblMessage.DisplayMessage(StatusMessages.ErrorMessage, "There is some problem while generating the database or database name doesn't avialible.");
}
}
Here is the code of "RollBackTheWholetransaction" method :
private Int32 RollBackTheWholetransaction(String DbName, Int32 HospitalId)
{
Int32 result = 0;
try
{
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
SqlConnection con = new SqlConnection();
con.ConnectionString = Connectionstring;
String sqlCommandText = "ALTER DATABASE [" + DbName + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE";
String sqlCommandText1 = "DROP DATABASE [" + DbName + "]";
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con);
sqlCommand1.ExecuteNonQuery();
ClsHospitals objHospiitals = new ClsHospitals();
String resultDbdelete = objHospiitals.DeleteHospital(HospitalId, Session["devSuperAdmin"].ToString());
if (resultDbdelete == "1")
{
result = 1;
}
else
{
result = 2;
}
}
else
{
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con);
sqlCommand1.ExecuteNonQuery();
}
con.Close();
con.Dispose();
result = 1;
}
catch (Exception ex)
{
result = 0;
}
return result;
}
And here is the code to check existence of db in Database :
public static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName)
{
string sqlCreateDBQuery;
bool result = false;
try
{
// tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes");
sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName);
using (tmpConn)
{
using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
{
if (tmpConn.State == System.Data.ConnectionState.Open)
{
tmpConn.Close();
tmpConn.Dispose();
}
tmpConn.Open();
tmpConn.ChangeDatabase("master");
int databaseID = (int)sqlCmd.ExecuteScalar();
tmpConn.Close();
result = (databaseID > 0);
}
}
}
catch (Exception ex)
{
result = false;
}
return result;
}
its the working code, hope it will work for you too....
You have to create your own installer by coding it all yourself. there are frameworks out there that make it much easyier.
like Windows Installer XML (WiX)
Windows installer
and more...
I would suggest you to have a look at WiX, worked with it and its quite easy and you can do much. Can be integrated in Visual Studio
I enabled MARS and still cant execute two SqlDataReaders in one connection,i searched for a solution to enable MARS by default using RegEdit by couldnt find any solution and still getting that error : There is already an open DataReader associated with this Command which must be closed first.
Here is the code :
public partial class student_Courses : System.Web.UI.Page
{
string connectionString = "";
string query1 = "";
string query2 = "";
string courseName = "";
string chapterName = "";
string chapterVideoName = "";
string courseValue = "";
SqlDataReader sr2 = null;
protected void Page_Load(object sender, EventArgs e)
{
query1 = "SELECT * FROM Courses";
query2 = "SELECT * FROM Chapters WHERE value='" + courseValue + "'";
connectionString = "Data Source=Prince-PC;" +
"Initial Catalog=Elearning;" +
"Integrated Security=True;"+
"MultipleActiveResultSets=True";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand command1 = new SqlCommand(query1, con);
SqlCommand command2 = new SqlCommand(query2, con);
if (con.State == ConnectionState.Closed)
con.Open();
using (SqlDataReader sr1 = command1.ExecuteReader())
{
while (sr1.Read())
{
courseName = sr1["name"].ToString();
courseValue = sr1["value"].ToString();
sr2 = command2.ExecuteReader();
while (sr2.Read())
{
chapterName = TextBox3.Text = sr2["name"].ToString();
chapterVideoName = Label2.Text = sr2["video_name"].ToString();
}
}
}
con.Close();
}
}
You need to dispose of sr2 via a using statement as done in this MSDN MARS example
// The following line of code requires
// a MARS-enabled connection.
productReader = productCmd.ExecuteReader();
using (productReader)
{
while (productReader.Read())
{
Console.WriteLine(" " +
productReader["Name"].ToString());
}
}