i have a problem with my Connection String ,
i have an Execute method with string parameter to Receive queries ,
public class Create_Connection
{
public static readonly string CONN_STRING =
ConfigurationManager.ConnectionStrings["TaskConnectionString"].ConnectionString;
public static readonly SqlConnection SqlConn = new SqlConnection(CONN_STRING);
public static readonly SqlConnection CONN = new SqlConnection(CONN_STRING);
public DataSet ExecuteSql(string sql)
{
SqlDataAdapter da;
DataSet ds;
if (CONN.State == ConnectionState.Open)
CONN.Close();
CONN.Open();
da = new SqlDataAdapter(sql, CONN_STRING);
ds = new DataSet();
da.Fill(ds);
CONN.Dispose();
CONN.Close();
return ds;
}
}
when i use it first time it's work will , but when the time of second query comes to use Execute method my program stop and give me this masseg : "The ConnectionString property has not been initialized" !! and the InnerException : " null " !!!
how that possible when it's work in the first time then change when the Conniction String is " Static readonly " !!
and Thanks in advance :) ..
Don't use static SqlCOnnection.
public class Create_Connection
{
public static readonly string CONN_STRING = ConfigurationManager.ConnectionStrings["TaskConnectionString"].ConnectionString;
public static readonly SqlConnection SqlConn = new SqlConnection(CONN_STRING);
//public static readonly SqlConnection CONN = new SqlConnection(CONN_STRING);
public DataSet ExecuteSql(string sql)
{
SqlDataAdapter da;
DataSet ds;
using (var CONN = new SqlConnection(CONN_STRING)) {
//if (CONN.State == ConnectionState.Open)
// CONN.Close();
CONN.Open();
da = new SqlDataAdapter(sql, CONN_STRING);
ds = new DataSet();
da.Fill(ds);
//CONN.Dispose();
CONN.Close();
}
return ds;
}
}
And create variable when you use it. Like this
public class Create_Connection
{
public static readonly string CONN_STRING = ConfigurationManager.ConnectionStrings["TaskConnectionString"].ConnectionString;
public static readonly SqlConnection SqlConn = new SqlConnection(CONN_STRING);
public DataSet ExecuteSql(string sql)
{
var ds = new DataSet();
using (var CONN = new SqlConnection(CONN_STRING)) {
CONN.Open();
var da = new SqlDataAdapter(sql, CONN_STRING);
da.Fill(ds);
CONN.Close();
}
return ds;
}
}
Related
I'm trying to fill a datagridview with SQL Server table data and I get an error:
ExecuteReader: Connection property has not been initialized.
How do I fix this ?
private void BlackListLoad()
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
BindingSource bs = new BindingSource();
var table = dt;
var connection =
#"Data Source=someone-someone\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
using (var con = new SqlConnection { ConnectionString = connection })
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.CommandText = #"SELECT * FROM [dbo].[Blacklist1]";
table.Load(cmd.ExecuteReader());
bs.DataSource = table;
ListGrid.ReadOnly = true;
ListGrid.DataSource = bs;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
You haven't given your SqlCommand a connection! As it states you need to do this. You can fix this by doing:
cmd.Connection = con; just before you execute the reader.
Read here for more information: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx
It also looks like you're not opening your connection, which can be fixed with:
con.Open();
With a new connection object, you do not need to check whether it's open, because it won't be.
Try it this way.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
}
}
I have a method on a form for getting a dataset, which i'm trying to call to populate a combobox but the table is not being found. What am I missing?
Here's the dataset method...
public partial class frmForm2 : Form
{
#region Variables
//Connection string
string conString = ("Data Source=L008##\\#####; Initial Catalog=FiT; Integrated Security=SSPI;");
//Data Variables
int maxRows;
int userID = frmForm1.user_ID;
#endregion
#region SQL Conn & Dataset
public DataSet GetDataSet(string connectionString)
{
//Create connection object
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlDataAdapter daAddWO = new SqlDataAdapter();
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = ("SELECT user_ID, user_name FROM table WHERE user_id=#userID");
//Initialise the parameter
cmd.Parameters.AddWithValue("#userID", userID);
//Pass the SQL query to the da
daAddWO.SelectCommand = cmd;
//Create the dataset
DataSet dsAddWO = new DataSet();
maxRows = dsAddWO.Tables[0].Rows.Count;
//Open the connection and fill the dataset
sqlCon.Open();
daAddWO.Fill(dsAddWO);
sqlCon.Close();
//Return the dataset
return dsAddWO;
}
#endregion
And here's where I'm trying to call the method...
public frmForm2()
{
InitializeComponent();
try
{
//Request dataset
DataSet dsAddWO = GetDataSet(conString);
DataRow dRow;
int incRow = 0;
dRow = dsAddWO.Tables[0].Rows[incRow];
comboBox1.Text = dRow.ItemArray.GetValue(1).ToString();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Any help much appreciated!
You must access to table 0 after you fill the Dataset because when You create a new dataset, it has no tables.
e.g.
public DataSet GetDataSet(string connectionString)
{
//Create connection object
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlDataAdapter daAddWO = new SqlDataAdapter();
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = ("SELECT user_ID, user_name FROM table WHERE user_id=#userID");
//Initialise the parameter
cmd.Parameters.AddWithValue("#userID", userID);
//Pass the SQL query to the da
daAddWO.SelectCommand = cmd;
//Create the dataset
DataSet dsAddWO = new DataSet();
//Open the connection and fill the dataset
sqlCon.Open();
daAddWO.Fill(dsAddWO);
sqlCon.Close();
maxRows = dsAddWO.Tables[0].Rows.Count;
//Return the dataset
return dsAddWO;
}
Hope it helps
Bye
You try to access the table before the dataset has been filled. A new dataset will not contain any tables.
I have some troubles with dataset in c#. I want to fill it with content from the database, but can't get it to work.
Here is my code:
from the main database layer containing the connection string
public static SqlCommand GetDbCommand(string sql)
{
if (dbconn.State.ToString().CompareTo("Open") != 0)
Open();
if (dbCmd == null)
{
dbCmd = new SqlCommand(sql, dbconn);
}
dbCmd.CommandText = sql;
return dbCmd;
}
This is the method that should fill the dataset from my DBMovie class
public static DataSet GetMovieSet()
{
DataSet movieSet = new DataSet();
string sql = "select * from Movie";
dbCmd = DBConnection.GetDbCommand(sql);
SqlDataAdapter da = new SqlDataAdapter();
da.Fill(movieSet);
DBConnection.Close();
return movieSet;
}
How do I connect the dataAdapter together with the database connection?
Connect the adapter to the command like so:
dbCmd = DBConnection.GetDbCommand(sql);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = dbCmd; //Add this
da.Fill(movieSet);
When I try to use the method GetCities(), it says:
Fill: SelectCommand.Connection property has not been initialized.
Can anyone please advise on what to do?
public class CitiesService
{
public DataSet DS;
public OleDbConnection myConnection;
public OleDbDataAdapter adapter;
public OleDbDataAdapter adapter2;
public CitiesService()
{
}
public DataSet GetCities()
{
OleDbCommand myCmd = new OleDbCommand("SPtblCities", myConnection);
myCmd.CommandType = CommandType.StoredProcedure;
OleDbDataAdapter Adapter = new OleDbDataAdapter();
Adapter.SelectCommand = myCmd;
DataSet dataSet = new DataSet();
try
{
Adapter.Fill(dataSet, "tblCities");
dataSet.Tables["tblCities"].PrimaryKey = new DataColumn[]
{
dataSet.Tables["tblCities"].Columns["CityID"]
};
}
catch (OleDbException ex)
{
throw ex;
}
return dataSet;
}
}
Yes, the connection was not initialized, it is null.
Replace
public OleDbConnection myConnection;
with
public OleDbConnection myConnection = new OleDbConnection(ConnectionString);
or in the method:
myConnection = new OleDbConnection(ConnectionString);
OleDbCommand myCmd = new OleDbCommand("SPtblCities", myConnection);
I would recommend you use this pattern and remember that some of these objects are disposable.
public class CitiesService
{
public DataSet DS;
public OleDbConnection myConnection;
public OleDbDataAdapter adapter;
public OleDbDataAdapter adapter2;
public CitiesService()
{
}
public DataSet GetCities()
{
using (DataSet dataSet = new DataSet())
{
using (OleDbConnection myConnection = new OleDbConnection(ConnectionString))
{
myConnection.Open();
using (OleDbCommand myCmd = myConnection.CreateCommand())
{
myCmd.CommandType = CommandType.StoredProcedure;
using (OleDbDataAdapter Adapter = new OleDbDataAdapter())
{
Adapter.SelectCommand = myCmd;
try
{
Adapter.Fill(dataSet, "tblCities");
dataSet.Tables["tblCities"].PrimaryKey = new DataColumn[] { dataSet.Tables["tblCities"].Columns["CityID"] };
}
catch (OleDbException ex)
{
throw ex;
}
}
}
myConnection.Close();
}
return dataSet;
}
}
}
I try to write a winform application:
I dislike below codes:
DataTable dt = new DataTable();
dt.Load(dr);
ds = new DataSet();
ds.Tables.Add(dt);
Above part of codes looks unsufficient.How can I best loading dataset?
public class LoadDataset
{
public DataSet GetAllData(string sp)
{
return LoadSQL(sp);
}
private DataSet LoadSQL(string sp)
{
SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand(sp, con);
DataSet ds;
try
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
finally
{
con.Dispose();
cmd.Dispose();
}
}
}
Here is a simple function I converted from VB to C# (http://www.developerfusion.com/tools/convert/vb-to-csharp/). I use this extensively.
Simple wrapper function to help return a dataset from and SQL statement via an existing connection.
This should have performance improvements over re-connected via a connection string each time. Wraps any SQL errors in to a custom format.
public System.Data.DataSet GetDataSet(string sqlStatement, System.Data.SqlClient.SqlConnection connection)
{
System.Data.DataSet functionReturnValue = default(System.Data.DataSet);
if (connection == null) {
throw new ArgumentNullException("connection");
}
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
System.Data.SqlClient.SqlDataAdapter adp = new System.Data.SqlClient.SqlDataAdapter();
System.Data.DataSet dset = new System.Data.DataSet();
try {
// Connect to the database
if (connection.State != ConnectionState.Open) {
connection.Open();
}
if (connection.State != ConnectionState.Open) {
throw new MyCustomException("Connection currently {0} when it should be open.", connection.State));
}
// Create a command connection
cmd = new System.Data.SqlClient.SqlCommand();
{
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlStatement;
}
//.ExecuteReader() 'Forward only Dataset
// Create a data adapter to store the inforamtion
adp = new System.Data.SqlClient.SqlDataAdapter();
dset = new DataSet();
{
adp.SelectCommand = cmd;
adp.Fill(dset, "Results");
}
// Return the resulting dataset to the calling application
functionReturnValue = dset;
}
catch (System.Data.SqlClient.SqlException objSE) {
functionReturnValue = null;
// Let the calling function known they stuffed up and give them the SQL to help out.
throw new JDDataException(System.String.Format("SQL :- {0}.", sqlStatement), objSE);
}
finally {
if ((cmd != null)) cmd = null;
if ((adp != null)) adp = null;
if ((dset != null)) dset = null;
}
return functionReturnValue;
}
public string GetSqlConnection()
{
return System.Configuration.ConfigurationManager.AppSettings["SqlConnectionString"];
}
public DataSet getDataSet(string sql)
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(GetSqlConnection());
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
conn.Close();
conn.Dispose();
da.Dispose();
return ds;
}