ASP.Net db connection issue - asp.net

I'm new to ASP.Net & SQL Server and have the following code:
protected void btnShowData_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=DESKTOP-RV7DDL4;Initial Catalog=Demodb
;User ID=DESKTOP-RV7DDL4\dbname;Password=test123";
cnn = new SqlConnection(connectionString);
SqlCommand command;
SqlDataReader dataReader;
String sql, Output = "";
sql = "Select TutorialID, TutorialName from demotb";
command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
lblName.Visible = false;
txtName.Visible = false;
lstLocation.Visible = false;
chkC.Visible = false;
chkASP.Visible = false;
rdMale.Visible = false;
rdFemale.Visible = false;
btnSubmit.Visible = false;
}
When I run the project I receive the following error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed.
I thought the connection was made so not sure why it says the db is closed?

Try to to explicitly open the connection via the Open method on the SQL connection class.
Perhaps a using statement is more appropriate here. Like so:
using (var cnn = new SqlConnection(connectionString))
{
// Use the connection
}

Thanks for your help. I re-jigged things around and added the .Open method and it works!
string connectionString = null;
SqlConnection cnn;
SqlCommand command;
string sql, Output = "";
connectionString = #"Data Source=DESKTOP-RV7DDL4\SQLEXPRESS;Initial Catalog=DemoDBase
;User ID=sa;Password=test1234";
cnn = new SqlConnection(connectionString);
sql = "Select TutorialID, TutorialName from demoTable";
cnn.Open();
command = new SqlCommand(sql, cnn);
SqlDataReader dataReader;
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();

Related

Connecting MS_SQL DB IN asp.net

I was trying to connectMs_sql database in asp.net but server error of network path not found... it is not able to establish connection to sql server...comes while in gridview it is taking it as sqldatasource perfectly
This for customized class to call the ADO.Net. Please use this and let me know if you have any doubts.
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;
}
}

command failing in login code in C# on ASP.NET

I am making a website using ASP.NET framework.
My code for login page is as below, it is very simple since I'm trying to see step by step where it is going wrong. The C# code is:
protected void userLogin(object sender, EventArgs e)
{
string encoded_pass = encrypt_pass(Password.Text);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString);
connection.Open();
using (SqlCommand cmd = new SqlCommand ("Select * from users where user_email= #email and user_password = #password"))
{
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#password", encoded_pass);
try
{
cmd.ExecuteNonQuery();
//SqlDataAdapter da = new SqlDataAdapter(cmd);
//DataTable dt = new DataTable();
//da.Fill(dt);
////Session["User"] = dt.Rows[0]["user_email"];
//Session["User_name"] = dt.Rows[0]["user_f_name"];
//loginlabel.Text = "Welcome, " + Session["User_name"];
}
catch
{
loginlabel.Text = "login error";
}
}
connection.Close();
}
Now every time I enter an email and password it always gives "login errorr".. Why the command is not executed?
Looks like you have declared the connection but haven't assigned it to the SqlCommand
using (SqlCommand cmd = new SqlCommand ("Select * from users where user_email= #email and user_password = #password",connection))
{
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#password", encoded_pass);
Note i added the connection variable in the cmd declaration.
In future you may also like catching your errors in development:
catch (Exception ex)
{
loginlabel.Text = "login error: "+ ex.Message;
}
This will help you know what is going wrong.

How to read uncommited transaction within sqltransaction?

i got a problem when using SQLTransaction in my .net framework 2.0 c# code
this is my code:
public bool register()
{
SqlConnection conn = DB.getInstance().getConnection();
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Transaction = sqlTransaction;
try
{
cmd = insertMembers(cmd);
cmd.ExecuteNonQuery();
SqlDataReader read = null;
cmd.CommandText = "SELECT * FROM members WHERE username='" + username + "'";
read = cmd.ExecuteReader();
while (read.HasRows)
{
id0 = (int)read["id0"];
}
cmd = insertMembersBalance(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersEPoint(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersVerify(cmd);
cmd.ExecuteNonQuery();
reset();
sqlTransaction.Commit();
}
catch(Exception e)
{
sqlTransaction.Rollback();
Console.WriteLine(e.ToString());
return false;
}
finally
{
conn.Close();
}
return true;
}
I can't get the id from members table to use for insert another records into another table.
is there any other solution?
You must call dr.Read() first than SqlDataReader dr = cmd.........
if (read.HasRows) // needs to be if not while or it will just loop
{
read.Read();
id0 = (int)read["id0"];
}
read.Close(); // need to close the reader before you can use the cmd
if you want to loop through all rows then
while (read.Read())
{
id0 = (int)read["id0"];
}

how to write select parameterized query in asp.net

Below code is written to call parameterized select query in asp.net
public bool checkConflictTime()
{
bool TimeExists = false;
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE starttime= #starttime AND endtime = #endtime";
SqlCommand sqlcommand = new SqlCommand(sql,sqlconn);
//sqlcommand.Connection = sqlconn;
//string sql = "CheckConflictTimings";
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));
sqlcommand.Parameters.Add(new SqlParameter("#endtime", ddlEndTime.SelectedItem.Text));
SqlDataAdapter da = new SqlDataAdapter(sql, sqlconn);
try
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
TimeExists = true;
}
}
catch (Exception ex)
{
}
finally
{
sqlconn.Close();
sqlconn.Dispose();
}
return TimeExists;
}
Is there something wrong? it threw error of :Must declare the scalar variable "#starttime"
when filling data adapter.
Try
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
Try
sqlcommand.Parameters.Add(new SqlParameter("starttime", ddlStartTime.SelectedItem.Text));
I don't think you need the # prefix when adding the parameter.
I think you're not passing your command as a SelectCommand to the adapter.
da.SelectCommand = sqlcommand;
Try
sqlcommand.Parameters.AddWithValue("#starttime",ddlStartTime.SelectedItem.Text);
instead of
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));

asp.net cannot update database

string ConnectionString = WebConfigurationManager.ConnectionStrings["dbnameConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(ConnectionString);
myConnection.Open();
try
{
string qry = "UPDATE customers SET firstname=#firstname WHERE cid=1";
SqlCommand insertQuery = new SqlCommand(qry, myConnection);
insertQuery.Parameters.Add(new SqlParameter("#firstname", txtFirstname.Text));
insertQuery.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ee)
{
}
Any suggestions?
A little cleanup of your code you may like to try (you should dispose IDisposable objects):
string ConnectionString = // ...
using (var connection = new SqlConnection(ConnectionString))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "UPDATE customers SET firstname = #firstname WHERE cid=1";
command.Parameters.AddWithValue("#firstname", txtFirstname.Text);
var rowsUpdated = command.ExecuteNonQuery();
}

Resources