ExecuteReader: Connection property has not been initialized - c#

ExecuteReader: Connection property has
not been initialized.
my coding is
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
// 2. Open the connection
conn.Open();
// 3. Pass the connection to a command object
//SqlCommand cmd = new SqlCommand("select * from Customers", conn);
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)
values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')");
//
// 4. Use the connection
//
// get query results
rdr = cmd.ExecuteReader();
// print the CustomerID of each record
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
finally
{
// close the reader
if (rdr != null)
{
rdr.Close();
}
// 5. Close the connection
if (conn != null)
{
conn.Close();
}
}
}
}
}

use this and pass connection object :
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')",conn);

After SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('....
Add
cmd.Connection = conn;
Hope this help

you have to assign connection to your command object, like..
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')");
cmd.Connection = conn;

All of the answers is true.This is another way. And I like this One
SqlCommand cmd = conn.CreateCommand()
you must notice that strings concat have a sql injection problem.
Use the Parameters
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx

You can also write this:
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (#project, #iteration)", conn);
cmd.Parameters.AddWithValue("#project",name1.SelectedValue);
cmd.Parameters.AddWithValue("#iteration",iteration.SelectedValue);

As mentioned you should assign the connection and you should preferably also use sql parameters instead, so your command assignment would read:
// 3. Pass the connection to a command object
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (#project, #iteration)", conn); // ", conn)" added
cmd.Parameters.Add("project", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;
cmd.Parameters.Add("iteration", System.Data.SqlDbType.NVarChar).Value = this.name1.SelectedValue;
//
// 4. Use the connection
//
By using parameters you avoid SQL injection and other problematic typos (project names like "myproject's" is an example).

I like to place all my sql connections in using statements. I think they look cleaner, and they clean up after themselves when your done with them. I also recommend parameterizing every query, not only is it much safer but it is easier to maintain if you need to come back and make changes.
// create/open connection
using (SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI")
{
try
{
conn.Open();
// initialize command
using (SqlCommand cmd = conn.CreateCommand())
{
// generate query with parameters
with cmd
{
.CommandType = CommandType.Text;
.CommandText = "insert into time(project,iteration) values(#name, #iteration)";
.Parameters.Add(new SqlParameter("#name", this.name1.SelectedValue));
.Parameters.Add(new SqlParameter("#iteration", this.iteration.SelectedValue));
.ExecuteNonQuery();
}
}
}
catch (Exception)
{
//throw;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
{
conn.Close;
}
}
}

Related

how to get a content from textboxes in a database table with a Button click event?

IWhat i wanna do
So I tried this code
but it coudnt get a connection with the Database. I the connection string is correct
SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into [kunde]Vorname()values(#nm)";
cmd.Parameters.AddWithValue("#nm", Vorname.Text);
cmd.Connection = con;
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "insert into [kunde]Nachname()values(#nmm)";
cmdd.Parameters.AddWithValue("#nmm", Nachname.Text);
cmdd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a == 1)
{
MessageBox.Show("Dateien bitte");
}
follow the following code. It inserts two columns into a table (tableName). Maintain proper space in SQL query as showing in below sample code. ALso, it's best practice to keep the code in a try-catch block to capture any error that occurs during DB operation.
try
{
SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into tableName(column1,column2) values(#nm,#nmm)";
cmd.Parameters.AddWithValue("#nm", Vorname.Text);
cmd.Parameters.AddWithValue("#nmm", Nachname.Text);
cmd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a == 1)
{
MessageBox.Show("Dateien bitte");
}
}
catch (Exception ex)
{
MessageBox.Show("Error:"+ex.ToString());
}

why isn't my c# insert query working?

what is the problem in my code?
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\extract step one\extract1.accdb;Persist Security Info=True";
String kerdes = Convert.ToString(textBox1.Text);
String valaszok = Convert.ToString(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(#kerdes, #valaszok)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#kerdes", OleDbType.VarChar).Value = kerdes;
cmd.Parameters.Add("#valaszok", OleDbType.VarChar).Value = valaszok;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
When I click the button it says:
Microsoft Office Access Database Engine
I made the database with Access. Any ideas?
OleDbCommand does not support named parameters - use ? instead:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");
I would also wrap both the command and connection in using blocks to ensure that the resources are disposed of properly.
You need to change your parameters to:
cmd.Parameters.AddWithValue("#kerdes", kerdes);
cmd.Parameters.AddWithValue("#valaszok", valaszok);
This needs to be done in addition to the above comment of changing your query to:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");

Error with Connection property has not been initialized

Well, I work little bit with C # and I'm starting to work with Database with C # now, I've googled in several places and I am unable to identify where it is wrong, everywhere say I need to open a connection, but it is already open .
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf");
con.Open();
try
{
string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)";
SqlCommand cmd = new SqlCommand(query);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Use using, takes care of the closing and disposal for you just in case you forget to do it explicitly. Put it inside the try, you have the connection open command outside the try so it wont catch any connection error. You probably want to look at parameterizing your command too.
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO [Table] (name, time) VALUES (#name,#time)", conn))
{
cmd.Parameters.AddWithValue("#name", "test");
cmd.Parameters.AddWithValue("#time", 1);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;Integrated Security=True;AttachDbFilename=C:\Users\Gustavo\Documents\Visual Studio 2013\Projects\hour\hour\Database1.mdf");
try
{
string query = "INSERT INTO [Table] (name, time) VALUES ('test',1)";
SqlCommand cmd = new SqlCommand(query,con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
you need to assign the command to the connection. eg:
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
//----
SqlCommand command = new SqlCommand(
queryString, connection);
//----
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}

C# and sql server

I've created a database and a table with 2 fields Id and Name.
Now I want to insert values on clicking a button the sammple code is given. it's not working.
using (SqlConnection connection = new SqlConnection(strConnection))
{
SqlCommand command =new SqlCommand("insert into Test (Id,Name) values(5,kk);",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
String values should be in quotes. This has not much to do with C#, more with T-SQL
Try this, and notice the kk;
SqlCommand command =
new SqlCommand("insert into Test (Id,Name) values(5,'kk');",connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Also I am assuming here that Id is not an auto-increment field. If it is, then you should not fill it.
As a side-node you should look at parameterized queries to prevent SQL injection.
In this instance, you need single quotes ' around the kk
insert into Test (Id,Name) values(5,'kk')
In general, you should use parameterised queries
try this:
SqlConnection conn = new SqlConnection();
SqlTransaction trans = conn.BeginTransaction();
try
{
using (SqlCommand cmd = new SqlCommand("insert into Test (Id,Name) values(#iD, #Name)", conn, trans))
{
cmd.CommandType = CommandType.Text;
cmd.AddParameter(SqlDbType.UniqueIdentifier, ParameterDirection.Input, "#iD", ID);
cmd.AddParameter(SqlDbType.VarChar, ParameterDirection.Input, "#Name", Name);
cmd.ExecuteNonQuery();
}
conn.CommitTransaction(trans);
}
catch (Exception ex)
{
conn.RollbackTransaction(trans);
throw ex;
}
Try this:
SqlConnection con = new SqlConnection('connection string here');
string command = "INSERT INTO Test(Id, Name) VALUES(5, 'kk')";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
String values should be between ' '
Verify your connection string
//add your connection string between ""
string connectionString = "";
using (var conn = new SqlConnection(connectionString))
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO pdf (Id, Name) VALUES (5, 'kk')";
conn.Open();
conn.ExecuteNonQuery();
conn.Close();
}
It looks like you have multiple problems with your current code.
You need to enclose string values in single quotes, as pointed out in other answers.
You need to enable remote connection to your SQL server.
Check the following link if you are using SQL server 2008.
How to enable remote connections in SQL Server 2008?
and for SQL Server 2005 see:
How to configure SQL Server 2005 to allow remote connections

How to retrieve the values in asp.net form from SQL Server 2005

I want the user entered values to get displayed in the form again.. my values get entered into the SQL Server database, but I don't know how to retrieve the values again in the form.. my code is:
SqlDataReader rdr = null;
SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=emp;Integrated Security=SSPI");
try
{
conn.Open();
SqlCommand cmd=new SqlCommand ("insert into timeday(project,iteration,activity,description,status,hour)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"','"+this .activity .SelectedValue +"','"+this.name2.Text+"','"+this.status .SelectedValue +"','"+this .Text1 .Text +"')",conn );
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
finally
{
if (rdr != null)
rdr.Close();
if (conn != null)
conn.Close();
}
You should:
avoid SQL injection and don't just concatenate together your SQL statements! Use parametrized queries instead!
put your SqlConnection and SqlCommand objects into using blocks
when you want to call an INSERT statement, definitely do not call .ExecuteReader() on your SqlCommand - use .ExecuteNonQuery() instead...
Try something like this:
string connStr = "Data Source=Silverage-6\\SQLSERVER2005;Initial Catalog=emp;Integrated Security=SSPI";
string queryStmt =
"INSERT INTO dbo.timeday(project, iteration, activity, description, status, hour) " +
"VALUES(#Project, #Iteration, #Activity, #Description, #Status, #Hour)";
using(SqlConnection conn = new SqlConnection())
using(SqlCommand _cmd = new SqlCommand(queryStmt, conn))
{
_cmd.Parameters.Add("#Project", SqlDbType.VarChar, 100);
_cmd.Parameters["#Project"].Value = this.name1.SelectedValue.Trim();
// add other parameters the same way....
conn.Open();
int result = _cmd.ExecuteNonQuery();
conn.Close();
}
It would be even better if you:
would retrieve the connection string from a config file once, centrally, and just pass it into this method
would retrieve the values to set from your web UI in your UI code, and then call this business method on a business logic object and pass in the values you've determined
Right now, you're wildly mixing UI code (retrieving the values from the dropdowns and textboxes) with database/business logic code - this is not a very solid design.....
Update: if you want to retrieve values and display them, you can use something like this:
public DataTable GetDataForProject(string projectName)
{
string connStr = "Data Source=Silverage-6\\SQLSERVER2005;Initial Catalog=emp;Integrated Security=SSPI";
string queryStmt =
"SELECT project, iteration, activity, description, status, hour " +
"FROM dbo.timeday " +
"WHERE project = #project";
DataTable resultTable = new DataTable();
using(SqlConnection conn = new SqlConnection())
using(SqlCommand _cmd = new SqlCommand(queryStmt, conn))
{
_cmd.Parameters.Add("#Project", SqlDbType.VarChar, 100);
_cmd.Parameters["#Project"].Value = projectName;
SqlDataAdapter dap = new SqlDataAdapter(_cmd);
dap.Fill(resultTable);
}
return resultTable;
}
Of course:
you might want to select based on other criteria (that would show up in your WHERE clause)
maybe you want to use a SqlDataReader and read that data into domain objects (instead of a DataTable)
but the basic setup - have a specific method, pass in criteria, read the data with SqlConnection and SqlCommand in using blocks - will remain the same.
Once you have the DataTable, you can bind it to an ASP.NET gridview:
DataTable projectData = GetDataForProject("MyProject");
gridView1.DataSource = projectData;
gridView1.DataBind();
After inserting you need to write a query to retrieve records.
Write this
SqlDataReader rdr = null;
SqlConnection conn = new SqlConnection("Data Source=Silverage-6\\SQLSERVER2005;Initial Catalog=emp;Integrated Security=SSPI");
try
{
conn.Open();
SqlCommand cmd=new SqlCommand ();
cmd.CommandText="insert into timeday(project,iteration,activity,description,status,hour)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"','"+this .activity .SelectedValue +"','"+this.name2.Text+"','"+this.status .SelectedValue +"','"+this .Text1 .Text +"')";
cmd.Connection=conn;
int i=cmd.ExecuteNonQuery();
if(i>0)
{
cmd.CommandText="Select * from timeday";
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}
}
finally
{
if (rdr != null)
rdr.Close();
if (conn != null)
conn.Close();
}

Categories

Resources