SellectCommad.connection Property not initialized - c#

When i debug my application, it gives an error that SelectCommand.Connection Property is not been initialized. i dont know what am i doing here wrong :s. I actually want to add a filter over my search on the textchanged event of a textbox.
public class ConnectionClass
{
static SqlConnection cn;
public static SqlConnection Connection()
{
string myConnection = ConfigurationManager.ConnectionStrings["_uniManagementConnectionString1"].ConnectionString;
if (cn != null)
{
cn = new SqlConnection(myConnection);
cn.Open();
}
return cn;
}
}
public class ClassDataManagement
{
SqlConnection cn = ConnectionClass.Connection();
public DataTable GetData(string SQL)
{
SqlCommand cmd = new SqlCommand(SQL, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
protected void TextBoxFilterText_TextChanged(object sender, EventArgs e)
{
ClassDataManagement dm = new ClassDataManagement();
string query = "Select CourseCode from _Courses where coursecode like'%" + TextBoxFilterText.Text.TrimEnd() + "%'";
dm.GetData(query);
GridViewCourses.DataBind();
}

That's because your cn variable is null, and not getting initialized. Yet another example why it's a bad idea to initialize and open database connections in a static method.
Try this:
public class ClassDataManagement
{
public DataTable GetData(string SQL)
{
string YourConnectionString = ConfigurationManager.ConnectionStrings["_uniManagementConnectionString1"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(YourConnectionString))
using (SqlCommand cmd = new SqlCommand(SQL, cn))
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
return dt;
}
}
With the SqlDataAdapter class, you don't need to explicitly call SqlConnection.Open(). The SqlDataAdapter.Fill() method handles all of the connection opening (and closing).
MSDN Reference on SqlDataAdapter.Fill()
As per the above reference, quoted:
The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

Open connection and close as soon as possible.
public DataTable GetData(string commandString)
{
var result = new DataTable();
using (var cn = new SqlConnection(ConfigurationManager.ConnectionStrings["_uniManagementConnectionString1"].ConnectionString))
using (var cmd = new SqlCommand(commandString, cn))
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(result);
}
return result;
}

Shouldn't that be
if (cn == null)
{
cn = new SqlConnection(myConnection);
cn.Open();
}

Although Sebastian's answer covers a good portion of what's wrong. Here is a more complete list.
You have SQL Injection issues. All queries should be parameterized otherwise you are asking for trouble. Especially when you are directly appending text entered by the user.
You are leaking resources: SqlConnection and SqlCommand. These need to be as close to the code that actually utilizes the connection and command as possible. Trust me, Windows is more than capable of handling all of the open/closing of connections through the build in connection pool. You don't need to maintain this yourself.
The code itself is brittle due to use of embedded SQL in your display layer. By way of example, let's say CourseCode is renamed to CourseId. You will have to search through and modify, potentially, a lot of code files just to make that change. There are multiple ways of limiting exposure to this issue; I'll leave that for you to research.
If I ran across this code in the wild, I would delete the ConnectionClass in its entirety. There is nothing that it is going to do for your that shouldn't be done elsewhere in a more robust manner.
Next I would delete the GetData() method. That is just bad code. You should never accept a full sql string and blindly execute it. There are a lot of security issues just in that one block of code.
Then I would rewrite the ClassDataManagement such that my SQL (if I really wanted it to stay embedded, which I wouldn't because I don't roll that way) was the container for all of my queries. I would have good methods like GetCourseByCourseCode(String courseCode) which would validate that the courseCode is in an expected format then pass it to my sqlcommand object as a parameter to the query.
For bonus points I'd expand on the above by looking at what calls could be better served by cached data. By having them in identified methods, it's much easier to pick and choose what can come from the cache vs what I really need to go across the network and run a query for.
Next, I would make sure that everywhere I made a SQL call, I had my SqlConnection, SqlCommand and readers wrapped in using clauses. It's the best way to ensure that everything is properly closed and disposed of prior to leaving the method. Anything less and you are inviting trouble.
Finally, I would highly consider using Enterprise Library for my data access. It's much better.

Having all given advices, to solve your current problem, you may try this way also:
public class ConnectionClass
{
static SqlConnection cn;
public static SqlConnection Connection()
{
string myConnection = ConfigurationManager.ConnectionStrings["_uniManagementConnectionString1"].ConnectionString;
return new SqlConnection(myConnection);
}
}
public class ClassDataManagement
{
public DataTable GetData(string SQL)
{
using (SqlConnection cn = ConnectionClass.Connection())
{
//SqlCommand cmd = new SqlCommand(SQL, cn);
SqlDataAdapter da = new SqlDataAdapter(SQL,cn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
......

public DataTable GetData()
{
using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
string expression = "Parameter value";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your Parameter Name",
SqlDbType.VarChar).Value = expression;
cmd.Connection = con;
using (SqlDataAdapter da = new SqlDataAdapter(SQL, cn))
{
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
}

Related

creating a list which works as inparameter for gridview

I'm working on a school development project and I'm quite new to development. I have been reading online but can't find the answer I'm looking for.
So far I have created a listbox in my Windows Forms application which I want to select all the values from one of my columns, and these should work as a inparameter to display data in my dataGridView based on the parameter.
I have created 70% of my project and this functionality is what is left. My database is in Azure and I can write to it and add new rows, but I can't read anything to my application when I run it.
code for listview, at first I just want to be able to select. Later on somehow write the choosen parameter to a variable that I can use as a condition in my dataGridView.
This is the code for my gridview so far I just want to display all data in it, but it's not showing anything.
namespace MyNamespace
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].
ConnectionString;
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand
(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue
(
"#companyName",
textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
MessageBox.Show("GJ");
}
}
// The code that is not filling my datagrid
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
}
}
My connection string is working it's already being able to insert data to the tables that I have.
The problem why you Grid isn't shown any data is that you try to bind a SqlDataReader to it. This isn't working, because the Grid doesn't support this as DataSource.
What you need as DataSource is DataTable, IList<T>, IBindingList<T>. In your case the DataTable would be the easiest solution. Try this out:
protected void DataEmployees()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select firstname,lastname FROM employees",con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
Notice that Methods are written Uppercase in C#. Further notice that you don't need to close the connection manually if you use a using-block. On the end of the using-block it's automatically closed/disposed.

Is this the right order to clear SqlDataAdapter and Sql Command Parameters and close the connection?

I am new to SQL and C# , I am using windows forms C#.
As shown in the example code, is this the correct order of clearing SqlDataAdapter and clearing Sql Command Parameters and closing the connection?
Please guide me. Thank you
public partial class C1 : UserControl
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand MyCommand = new SqlCommand();
DataTable DataTable = new DataTable();
SqlDataAdapter Sql_Data_Adapter = new SqlDataAdapter();
public C1()
{
InitializeComponent();
DataTable.Rows.Clear();
DataTable.Columns.Clear();
MyConnection.Open();
MyCommand.CommandText = "SELECT * FROM taqble1";
MyCommand.Connection = MyConnection;
Sql_Data_Adapter.SelectCommand = MyCommand;
Sql_Data_Adapter.Fill(DataTable);
buttonMD1_1.Text = Convert.ToString(DataTable.Rows[0]["Button_Text"]);
buttonMD1_2.Text = Convert.ToString(DataTable.Rows[1]["Button_Text"]);
buttonMD1_3.Text = Convert.ToString(DataTable.Rows[2]["Button_Text"]);
buttonMD1_4.Text = Convert.ToString(DataTable.Rows[3]["Button_Text"]);
// I did not clear DataTable because later I will use it
MyCommand.Parameters.Clear();
Sql_Data_Adapter.Dispose();
MyConnection.Close();
}
The order of distruction of your objects is not too important here, the important thing is to avoid global variables and be sure to always dispose the disposable objects
public C1()
{
InitializeComponent();
using(SqlConnection MyConnection = new SqlConnection(...))
using(SqlCommand MyCommand = new SqlCommand("SELECT * FROM taqble1", MyConnection))
using(SqlDataAdapter adapter = new SqlDataAdapter(MyCommand))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
.... button code ....
}
}
The Using Statement closes and dispose the disposable objects also in case of Exceptions. The DataTable object is local, so when the code exits (and you don't need it anymore) it will be automatically disposed.
Avoid keeping a global object for the connection, there is a Connection Pooling infrastructure that allows to get good performance in using this kind of object. The SqlCommand is lightweight and it is easily rebuilt when you need it, the SqlDataAdapter instead is meant to be reused for updating when you bind the DataTable to a grid, so sometimes is necessary to keep it global.
In your context, I think you should simply use a SqlDataReader instead of an SqlDataAdapter
public C1()
{
InitializeComponent();
using(SqlConnection MyConnection = new SqlConnection(...))
using(SqlCommand MyCommand = new SqlCommand("SELECT * FROM taqble1", MyConnection))
{
DataTable dt = new DataTable();
using(SqlDataReader reader = MyCommand.ExecuteReader())
{
dt.Load(reader);
.... button code ....
}
}
}
I see a lot of time this kind of error, in particular around the connection object. People thinks to get better performances keeping it global. That's not true and both your local and remote resources are stressed with a global connection object.

Replacement for SqlConnection and SqlCommand

I have been writing a lot of open and close connection to a Microsoft SQL Server database. I'm not sure whether it is the latest technique available for .NET. Is there any latest .NET function that I'm missing?
Example code:
protected string InjectUpdateToProductDBString(string Command, TextBox Data, string TBColumn)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AuthenticationDBConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#" + TBColumn, Data.Text.ToString());
cmd.ExecuteNonQuery();
con.Close();
return "Data successfully updated";
}
Is there any replacement for this fussy code technique? Just a discussion to improve my code technique.
There are other ways to write it and other tools you could use (like Entity Framework).
However, I recommend that you create a static function (or several) for your data access calls.
protected DataTable ExecuteSqlDataReader(string connection, string sqlQuery, SqlParameter[] cmdParams)
{
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand cmd = new MySqlCommand(sqlQuery, con);
cmd.Parameters = cmdParams;
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
sda.Command.Close();
return dt;
}
Create methods for Getting a dataTable, One value, ExecuteNonQuery, and even break it further down by abstracting out the SqlCommand creation to it's own method.
In any project, this code should be written only a few times.
Make sure that you enclose your SqlConnection in using statement. It will ensure the connection is closed even if there is an exception. Also, enclose your SqlCommand object in using statement, that will ensure disposal of unmanaged resources.
In your current code snippet if there is an exception at cmd.ExecuteNonQuery(); then your line con.Close would not execute, leaving the connection open.
So your method could be like:
protected string InjectUpdateToProductDBString(string Command, TextBox Data, string TBColumn)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AuthenticationDBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(command, con))
{
cmd.Parameters.AddWithValue("#" + TBColumn, Data.Text.ToString());
cmd.ExecuteNonQuery();
}
}
return "Data successfully updated";
}
Later you can return a DataTable or List<T> for your returned rows from the query.
If you want to move away from ADO.Net, then you can look into Object-Relation Mapping (ORM), which would provide you objects based on your database and easier way to manage your code base. Entity framework is one of them. You may see https://stackoverflow.com/questions/132676/which-orm-for-net-would-you-recommend
private SqlConnection GetConnection()
{
var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["AuthenticationDBConnectionString"].ConnectionString);
con.Open();
return con;
}
protected string InjectUpdateToProductDBString(string Command, TextBox Data, string TBColumn)
{
using (var con = GetConnection())
{
using (var cmd = con.CreateCommand())
{
cmd.Parameters.AddWithValue("#" + TBColumn, Data.Text);
cmd.ExecuteNonQuery();
return "Data Succesfully Updated";
}
}
}

Is the database connection in this class "reusable"?

I'm new to asp.net so this might be really basic question, but i cant figure it out.
I found a bit of code on the internet, that connects to database. And i created a namespace and some classes to use the same code in different projects.
The code and my class is the following:
namespace databaseFunctions
{
public class databaseConnection
{
private static string databaseConnectionString()
{
return "DRIVER={MySQL ODBC 5.1 Driver}; ........";
}
public static DataTable getFromDatabase(string SQL)
{
DataTable rt = new DataTable();
DataSet ds = new DataSet();
OdbcDataAdapter da = new OdbcDataAdapter();
OdbcConnection con = new OdbcConnection(databaseConnectionString());
OdbcCommand cmd = new OdbcCommand(SQL, con);
da.SelectCommand = cmd;
da.Fill(ds);
try
{
rt = ds.Tables[0];
}
catch
{
rt = null;
}
return rt;
}
public static Boolean insertIntoDatabase(string SQL)
{
OdbcDataAdapter da = new OdbcDataAdapter();
OdbcConnection con = new OdbcConnection(databaseConnectionString());
OdbcCommand cmd = new OdbcCommand(SQL, con);
con.Open();
try
{
cmd.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
}
}
There is no problem getting data from database, or insert data into some database.
But. when i try to get the last_insert_id() from the mysql database. i only get a zero.
This is why i think that this piece of code I've created and copied from internet, creates a new connection for every time i call the "getFromDatabase(SQL)"
Is there anyone that could help me with fixing this class getFromDatabase() to keep the databaseconnection alive until i tell the program to abandon the connection?
I guess it is the "new OdbcConnection" that should be changed? Is it possible to check if there already is a connection alive?
I've done this hundreds of times in classic asp, but now, with classes and stuff. I'm totally lost.
The problem you face is that you've coded yourself into a "new connection per action" corner. What you really want to aim for,and is considered best practice, is "new connection per batch of actions".
What I recommend in this case is to open connection when required, and close when disposed. What we'll do is move the odbc adapters to a larger scoped variable so that it can be accessed within the class.
namespace databaseFunctions
{
public class databaseConnection:IDisposable
{
private OdbcConnection con;
private string connectionString;
public databaseConnection(string connectionString){
this.connectionString = connectionString;
}
public void OpenConnection(){
if (con == null || con.IsClosed ){ // we make sure we're only opening connection once.
con = new OdbcConnection(this.connectionString);
}
}
public void CloseConnection(){
if (con != null && con.IsOpen){ // I'm making stuff up here
con.Close();
}
}
public DataTable getFromDatabase(string SQL)
{
OpenConnection();
DataTable rt = new DataTable();
DataSet ds = new DataSet();
OdbcCommand cmd = new OdbcCommand(SQL, con);
da.SelectCommand = cmd;
da.Fill(ds);
try
{
rt = ds.Tables[0];
}
catch
{
rt = null;
}
return rt;
}
public Boolean insertIntoDatabase(string SQL)
{
OpenConnection();
OdbcCommand cmd = new OdbcCommand(SQL, con);
con.Open();
try
{
cmd.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
}
// Implementing IDisposable method
public void Dispose(){
CloseConenction();
}
}
}
Now the next time you use your class do something like
using (DatabaseConnection db = new DatabaseConnection()){
db.InsertIntoDatabase(...);
db.GetLastInsertID();
db.GetFromDatabase(...);
}
At the end of that code block, because it is IDisposeable, it will close that connection for you in the dispose method.
Things I changed:
implemented IDisposable interface
changed methods from static to class methods.
added new methods for opening closing connection
moved connection variable to class level scope
added an argument to the constructor that lets you pass in a connection string (you should put this connection string in you Web.Config
Edits:
constructor takes in connectionString per suggestion.
Yes, the code you posted is creating a new database connection every time a method is called, but that's not a problem. The problem is that it is not disposing the connection properly. The way to handle something like this is as follows:
using (OdbcConnection con = new OdbcConnection("yourconnectionsstring"))
{
con.open();
OdbcCommand command = new OdbcCommand("command_text",con);
command.ExecuteQuery(); //or what ever you need to do
}
That way the connection is being disposed properly since using is just syntactic sugar for try/finally
What you need to do is execute the 2 sql statements in the same transaction in a way that you insert the record in the first sql statement and retrieve the last inserted id on the next insert before ending the transaction. For example:
using (OdbcConnection con = new OdbcConnection("yourconnectionsstring"))
{
con.open();
OdbcTransaction tran = con.BeginTransaction()
OdbcCommand command = new OdbcCommand("first_sql_statement_here",con);
command.ExecuteNonQuery();
command.CommandText = "select last_insert_id();";
int result =command.ExecuteScalar();
tran.commit();
}
That is pretty much the idea.
You should let the connection pool handle your connections; That means you Close() every connection as soon as possible, and only create a new one at the last possible moment.
So yes - keep creating new ones for separate transactions.

Read SQL Table into C# DataTable

I've read a lot of posts about inserting a DataTable into a SQL table, but is there an easy way to pull a SQL table into a .NET DataTable?
Here, give this a shot (this is just a pseudocode)
using System;
using System.Data;
using System.Data.SqlClient;
public class PullDataTest
{
// your data table
private DataTable dataTable = new DataTable();
public PullDataTest()
{
}
// your method to pull data from database to datatable
public void PullData()
{
string connString = #"your connection string here";
string query = "select * from table";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
conn.Close();
da.Dispose();
}
}
var table = new DataTable();
using (var da = new SqlDataAdapter("SELECT * FROM mytable", "connection string"))
{
da.Fill(table);
}
Lots of ways.
Use ADO.Net and use fill on the data adapter to get a DataTable:
using (SqlDataAdapter dataAdapter
= new SqlDataAdapter ("SELECT blah FROM blahblah ", sqlConn))
{
// create the DataSet
DataSet dataSet = new DataSet();
// fill the DataSet using our DataAdapter
dataAdapter.Fill (dataSet);
}
You can then get the data table out of the dataset.
Note in the upvoted answer dataset isn't used, (It appeared after my answer)
It does
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
Which is preferable to mine.
I would strongly recommend looking at entity framework though ... using datatables and datasets isn't a great idea. There is no type safety on them which means debugging can only be done at run time. With strongly typed collections (that you can get from using LINQ2SQL or entity framework) your life will be a lot easier.
Edit: Perhaps I wasn't clear: Datatables = good, datasets = evil. If you are using ADO.Net then you can use both of these technologies (EF, linq2sql, dapper, nhibernate, orm of the month) as they generally sit on top of ado.net. The advantage you get is that you can update your model far easier as your schema changes provided you have the right level of abstraction by levering code generation.
The ado.net adapter uses providers that expose the type info of the database, for instance by default it uses a sql server provider, you can also plug in - for instance - devart postgress provider and still get access to the type info which will then allow you to as above use your orm of choice (almost painlessly - there are a few quirks) - i believe Microsoft also provide an oracle provider. The ENTIRE purpose of this is to abstract away from the database implementation where possible.
Vendor independent version, solely relies on ADO.NET interfaces; 2 ways:
public DataTable Read1<T>(string query) where T : IDbConnection, new()
{
using (var conn = new T())
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = query;
cmd.Connection.ConnectionString = _connectionString;
cmd.Connection.Open();
var table = new DataTable();
table.Load(cmd.ExecuteReader());
return table;
}
}
}
public DataTable Read2<S, T>(string query) where S : IDbConnection, new()
where T : IDbDataAdapter, IDisposable, new()
{
using (var conn = new S())
{
using (var da = new T())
{
using (da.SelectCommand = conn.CreateCommand())
{
da.SelectCommand.CommandText = query;
da.SelectCommand.Connection.ConnectionString = _connectionString;
DataSet ds = new DataSet(); //conn is opened by dataadapter
da.Fill(ds);
return ds.Tables[0];
}
}
}
}
I did some performance testing, and the second approach always outperformed the first.
Stopwatch sw = Stopwatch.StartNew();
DataTable dt = null;
for (int i = 0; i < 100; i++)
{
dt = Read1<MySqlConnection>(query); // ~9800ms
dt = Read2<MySqlConnection, MySqlDataAdapter>(query); // ~2300ms
dt = Read1<SQLiteConnection>(query); // ~4000ms
dt = Read2<SQLiteConnection, SQLiteDataAdapter>(query); // ~2000ms
dt = Read1<SqlCeConnection>(query); // ~5700ms
dt = Read2<SqlCeConnection, SqlCeDataAdapter>(query); // ~5700ms
dt = Read1<SqlConnection>(query); // ~850ms
dt = Read2<SqlConnection, SqlDataAdapter>(query); // ~600ms
dt = Read1<VistaDBConnection>(query); // ~3900ms
dt = Read2<VistaDBConnection, VistaDBDataAdapter>(query); // ~3700ms
}
sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());
Read1 looks better on eyes, but data adapter performs better (not to confuse that one db outperformed the other, the queries were all different). The difference between the two depended on query though. The reason could be that Load requires various constraints to be checked row by row from the documentation when adding rows (its a method on DataTable) while Fill is on DataAdapters which were designed just for that - fast creation of DataTables.
Centerlized Model: You can use it from any where!
You just need to call Below Format From your function to this class
DataSet ds = new DataSet();
SqlParameter[] p = new SqlParameter[1];
string Query = "Describe Query Information/either sp, text or TableDirect";
DbConnectionHelper dbh = new DbConnectionHelper ();
ds = dbh. DBConnection("Here you use your Table Name", p , string Query, CommandType.StoredProcedure);
That's it. it's perfect method.
public class DbConnectionHelper {
public DataSet DBConnection(string TableName, SqlParameter[] p, string Query, CommandType cmdText) {
string connString = # "your connection string here";
//Object Declaration
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
try {
//Get Connection string and Make Connection
con.ConnectionString = connString; //Get the Connection String
if (con.State == ConnectionState.Closed) {
con.Open(); //Connection Open
}
if (cmdText == CommandType.StoredProcedure) //Type : Stored Procedure
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Query;
if (p.Length > 0) // If Any parameter is there means, we need to add.
{
for (int i = 0; i < p.Length; i++) {
cmd.Parameters.Add(p[i]);
}
}
}
if (cmdText == CommandType.Text) // Type : Text
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
if (cmdText == CommandType.TableDirect) //Type: Table Direct
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
cmd.Connection = con; //Get Connection in Command
sda.SelectCommand = cmd; // Select Command From Command to SqlDataAdaptor
sda.Fill(ds, TableName); // Execute Query and Get Result into DataSet
con.Close(); //Connection Close
} catch (Exception ex) {
throw ex; //Here you need to handle Exception
}
return ds;
}
}

Categories

Resources