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;
}
}
}
Related
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;
}
}
error: not all code path returns a value,
i'm trying to return a dataset from function but getting this error,
code:
public partial class crystalReport_manual : System.Web.UI.Page
{
String conStr = WebConfigurationManager.ConnectionStrings["LoginDatabaseConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
DataSet1 ds = Dataset_load("Select * from login");
ReportDocument rd = new ReportDocument();
rd.Load(Server.MapPath("CrystalReport.rpt"));
rd.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rd;
}
public DataSet1 Dataset_load(String query)
{
SqlConnection sqlcon = new SqlConnection(conStr);
SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon);
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom);
// DataSet ds = new DataSet("CRDataSet");
try
{
sqlcon.Open();
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataSet1 ds = new DataSet1();
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
return ds;
}
catch (Exception exc)
{
Response.Write(exc.Message);
}
finally
{
sqlcon.Close();
}
}
What if an exception occur, your catch or finally block should return some value.
Since you are only closing the connection in finally you can use using block like:
public DataSet1 Dataset_load(String query)
{
DataSet1 ds = new DataSet1();
using(SqlConnection sqlcon = new SqlConnection(conStr))
using(SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon))
using (SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom))
{
try
{
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
return ds;
}
catch (SqlException se)
{
Response.Write(se.Message);
return null;
}
catch (Exception exc)
{
Response.Write(exc.Message);
return null;
}
}
}
using internally translates to try-finally block, and works with those which implements IDisposable, in finally block it calls the Dispose method, since SqlConnection, SqlCommand, and SqlDataAdapter, all implements IDisposable with using statement it will call Dispose at the end which would close the connection.
public DataSet1 Dataset_load(String query)
{
DataSet1 ds = new DataSet1();
using(SqlConnection sqlcon = new SqlConnection(conStr))
using(SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon))
using (SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom))
{
try
{
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
//return ds;
}
catch (SqlException se)
{
Response.Write(se.Message);
//return null;
}
catch (Exception exc)
{
Response.Write(exc.Message);
//return null;
}
}
return ds;
}
Building off the previous user's response, if an empty DataSet is returned at the end of your using statement, you can always check ds.Tables.Count to see if anything was returned. Otherwise you can use the logic above and null check
how we can export or import data from or to to Datagridview from Excel or Access file??
I need to know the code for export and import..any one help please
try this:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(#"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "Net-informations.com");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
}
}
Here is another tutorial
or just use google
I'll try to extend previous post with Access sample:
DataTable LoadSchemaFromAccess(string szFilePath)
{
System.Data.OleDb.OleDbCommand cmd;
try
{
System.Data.OleDb.OleDbConnection cnn = new System.Data.OleDb.OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", szFilePath));
cnn.Open();
System.Data.DataTable schemaTable = cnn.GetSchema("Tables");
cnn.Close();
return schemaTable;
}
catch (exception e)
{
MessageBox.Show(e.Message);
return null;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
}
}
string LoadDataFromAccess(string szTableName )
{
string GetData = L"SELECT * FROM " + szTableName;
System.Data.OleDb.OleDbCommand cmd;
string szColumns = "";
try
{
System.Data.OleDb.OleDbConnection cnn = new System.Data.OleDb.OleDbConnection
(string.Format(L"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", szPath));
cnn.Open();
System.Data.DataTable dt = new System.Data.DataTable();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = cnn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = GetData;
OleDbDataAdapter adt = new OleDbDataAdapter(cmd);
adt.SelectCommand = cmd;
adt.Fill(dt);
cnn.Close();
return dt;
}
catch (exception e)
{
MessageBox.Show(e.Message);
return null;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
}
}
Hope this helped.
Is this good approach to get data from stored procedure? For example procedure is making select * from base. Here is my code but I need help with dataset and adapter:
public static DataSet Osvezi(string naziv_tablice)
{
SqlCommand cmd = null;
DataSet dataset = null;
SqlConnection konekcija = new SqlConnection(ConfigurationManager.AppSettings["skripta"]);
if (konekcija != null)
{
try
{
if (konekcija.State == ConnectionState.Closed)
konekcija.Open();
cmd = new SqlCommand();
cmd.Connection = konekcija;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Osvezi";
cmd.Parameters.Add(new SqlParameter("#tablica", SqlDbType.Int)).Value = naziv_tablice;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Fill the DataSet using default values for DataTable names, etc
da.Fill(dataset);
return dataset;
}
catch (Exception ee)
{
//Obravnava napak
}
finally
{
konekcija.Close();
konekcija.Dispose();
cmd.Dispose();
}
return dataset;
}
return dataset;
}
Try this one instead:
public static DataSet Osvezi(string naziv_tablice)
{
try
{
using (SqlConnection konekcija = new SqlConnection(ConfigurationManager.AppSettings["skripta"]))
{
konekcija.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = konekcija;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Osvezi";
cmd.Parameters.AddWithValue("#tablica", naziv_tablice??DBNull.Value);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
// Fill the DataSet using default values for DataTable names, etc
DataSet dataset = new DataSet();
da.Fill(dataset);
return dataset;
}
}
}
}
catch (Exception ee)
{
//Obravnava napak
}
return null;
}
Please correct the following.
You don't need to open the connection.
There shouldn't be any command.ExecuteNonQuery.
The parameter in the method is string but the datatype of SqlParameter is SqlDbType.Int.
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;
}