I am writing web application in C#, and database is MSSQL Express 2012.
When i use SqlDataAdapter i get the Error:
ExecuteReader requires an open and available Connection.
The connection's current state is connecting.
SqlDataAdapter da = new SqlDataAdapter(sql, sqlConn);
da.Fill(dt);
I can not figure how to fix it. Thankss
Try this :
lock(conn)
{
DataTable dt = new DataTable();
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
{
sqlDataAdapter.Fill(dt);
}
}
Related
all I try to load data from sql by following code using SQL server. I checked connection is normal and most sql are available to load. But in certain cases, I can't load data with following error:
"The conversion of the varchar value '2863289685' overflowed an int column.
The statement has been terminated."
and that sql is runnable in sql server management studio, but can't load by following code, please help me with possible solution, thanks!
try
{
SqlCommand command = new SqlCommand(sql, conn);
command.CommandTimeout = 0;
SqlDataAdapter sqlDa = new SqlDataAdapter(command);
DataSet ds = new DataSet();
sqlDa.Fill(ds);
Console.WriteLine(ds.Tables.Count);
dt = ds.Tables[0];
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
I have been attempting this several different ways based on searches I have found online but am having the same result.
I am working on an SSIS Script Task that will execute a stored procedure that needs a TVP parameter to be passed into it. I have all that wired up and working properly, but when it gets to the da.Fill(resultDT)
I get the error:
Fill: SelectCommand.Connection property has not been initialized.
OleDbDataAdapter A = new OleDbDataAdapter();
DataTable dt = new DataTable();
A.Fill(dt, Dts.Variables["User::Companies"].Value);
DataTable resultDT = new DataTable();
using (SqlConnection sqlcon = (SqlConnection)(Dts.Connections["RegistryConnection"].AcquireConnection(Dts.Transaction) as SqlConnection))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = sqlcon;
cmd.CommandText = "[Registry].[GetClientData_ByCompanyIDs]";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#companyIDs", dt);
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
da.Fill(resultDT);
Dts.Variables["User::Clients"].Value = resultDT;
}
}
}
Any ideas what I am missing? Hoping it's something easy that I am overlooking.
Issue was that I was using an OLEDB Connection Manager, which apparently cannot be cast to an SQLConnection in the way I was doing it.
Needed to setup ADO.Net Connection Manager and then the SQLConnection cast worked as intended.
Problem Solved.
I'm creating a social Networking Website for that I used "Social Networking Website in ASP.NET - Open Source" from
http://www.c-sharpcorner.com/UploadFile/rahul4_saxena/social-networking-website-in-Asp-Net-open-source-project/
When I tried to run the project on my Visual Studio 2012 edition it is showing error like below,
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Source Error:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Summary description for DataBaseClass
/// </summary>
public class DataBaseClass
{
SqlDataAdapter da;
SqlConnection con;
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
public DataBaseClass()
{
//
// TODO: Add constructor logic here
//
}
public void ConnectDataBaseToInsert(string Query)
{
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
public DataSet ConnectDataBaseReturnDS(string Query)
{
ds = new DataSet();
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return ds;
}
public DataTable ConnectDataBaseReturnDT(string Query)
{
dt = new DataTable();
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return dt;
}
}
Visual studio pointing the error here da.Fill(dt).
I have spent 2 days to debug this error but still I couldn't. Please help me.
It is very simple. Your code is not able to connect to the database. Open Server Explorer in Visual Studio and connect to your database to confirm you are able to connect. And then get your connection string right.
And you do have a database, right?
I need some help because I've been trying different things but nothing seems to work properly the question itself is the one below.
How can I bind data to a grid-view in Visual Studio 2013 with a local SQL Server database using the code behind C# ?
Here is the C# I'm trying:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Guillermo\Desktop\HorsensHospital\App_Data\HospitalDB.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
GridView1.DataSource = ds;
GridView1.DataBind();
cmd.ExecuteNonQuery();
con.Close();
}
You just assing your empty DataSet to your Gridview's DataSource.
You need to use .Fill method fo fill your DataSet of SqlDataAdapter. You don't need to use ExecuteNonQuery. This method just executes your query. It doesn't return any data or something as a result.
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter. You don't need to .Close() your database connections and objects when you use it.
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]";
using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
You should use statement like this :
when you use SqlDataAdapter you should fill an dataset with Fill Method
then set the DataSource Properties Of GridView
SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
You have missed Fill method to fill your your dataset that is why i think you are not able to display gridview.
Fill Method is very Improtant method Bcoz whatever your query is returning that should be filled into your dataset & then that dataset is binded by your Gridiview
Hope this will help you
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Guillermo\Desktop\HorsensHospital\App_Data\HospitalDB.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
cmd.ExecuteNonQuery();
con.Close();
}
Note : You need to create your connection string in Web.Config. Bcoz If you have created your connection string there then you will not need to create that again. Once creating there you will just need to call that from the Web.config
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString);
This is the syntax for calling connection string from web.config
When i analyzed my code from Visual Studio 2013 some warnings appear that "Do not dispose objects multiple times " it also stated that object conn disposed multiple times in object but as i know if i did not use this object multiple times in object than i cant achieve my goals.
so kindly tell me how i can remove this warning ?
here is my code :
private void GetData()
{
DataTable dt = new DataTable();
_connString = ConfigurationManager.AppSettings["connString"];
using (SqlConnection conn = new SqlConnection(_connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("select * from ref_CourseRegistration_Users", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
if (ds.Tables[0].Rows.Count > 0)
{
grdUsers.DataSource = ds;
grdUsers.DataBind();
}
}
}
here is screenshot of my analysis :
Here if you are using the using statement
using (SqlConnection conn = new SqlConnection(_connString))
no need to close the connection again
so conn.Close(); is not required.
It'll automatically dispose the object.
When you are opening a connection in using block, the using block will automatically call the Dispose() method while leaving the using block scope.
So, conn.Close(); is not required in your code.