I caņ't seem to get around this error message: ExecuteNonQuery: Connection property has not been initialized
It refers to a cmd.ExecuteNonQuery();
I'm not really sure what is going on, maybe the insert is not correct, but here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace md2
{
public partial class Form2 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=MD2;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form2()
{
InitializeComponent();
}
private void label2_Click(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void button2_Click(object sender, EventArgs e)
{
if (izd_adr.Text != "" && izd_nos.Text != "") {
cn.Open();
cmd.CommandText = "insert into Publisher (pu_id, pub_name, adress) values ("+null+"'Elina', 'Kalnina')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Ir pievienots");
cn.Close();
new Form1().Show();
}
}
}
}
I followed a tutorial in how to do this, but I'm getting this error.
That Database looks like this:
This seems like a easy mistake somewhere, but is really frustrating...
You need to set the connection property on the command object:
cmd.Connection = cn;
An easier way to manage this is to let the SqlConnection create the command, which associates the SqlCommand with the SqlConnection: ie
cmd = cn.CreateCommand();
move cmd.Connection = cn; into the button click event. When you click the button currently, cmd has no connection property.
You must pass the SqlConnection to the SqlCommand, either with SqlCommand.Connection, pass it in the constructor or use CreateCommand().
I recommend creating a new SqlCommand and SqlConnection object when needed and refrain from caching them. SQL server does connection pooling anyway:
using (SqlConnection connection = new SqlConnection(...))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("....", connection))
{
}
}
Change the Connection String as given below If you are using Compact 4.0 Database
SqlConnection cn = new SqlConnection(#"Data Source=|DataDirectory|\MD2.sdf");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
you can change the Provider Name according to you SQL Server Name.
and Move cmd.Connection = cn; into the button2_click event.
I agree with S. Laurijssen, and would like to emphasize that his example uses using blocks. Because SqlConnection and SqlCommand both implement IDisposable, each is automatically closed properly at the end of the block. My example put this in a class called Common.
My only, additional suggestion would be that you create a public static method that generates a SqlConnection object, opens it, and then returns the instantiated, opened connection. You can then do something like this:
using (SqlConnection cn = Common.GetConnection())
{
using (SqlCommand cmd = new SqlCommand("[your SQL command here]", cn))
{
}
}
With this pattern, you do not need to remember to open or close your SqlConnection, and your code is cleaner.
Related
I have bellow class in my project that can help me to run SQL commands directly. in my computer it works fine. but when I published to web server after about 5 or 6 times that I called in page I got memory low error. that error cleaned after about 20 minutes. but it happens again and again.
using System;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Data;
using System.Data.Linq;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
public class FirstClass
{
SqlConnection con;
public SqlCommand cmd;
DataTable dt;
SqlDataAdapter da;
public FirstClass()
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["WebSiteConnectionString"].ConnectionString);
cmd = new SqlCommand();
dt = new DataTable();
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
}
public DataTable dbSelect(string sql)
{
DataTable dttt = new DataTable();
try
{
cmd.CommandText = sql;
con.Open();
da.Fill(dt);
con.Close();
return dt;
}
catch
{
return dttt;
}
}
public void exeSp(string spName)
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = spName;
cmd.ExecuteNonQuery();
con.Close();
}
public void exeSqlCmd(string sql)
{
try
{
cmd.CommandText = sql;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch { }
}
}
This mostly happens when I use the first method. Of course, the number of records that are fetched is also important. The higher the number of records fetched, the faster the memory shortage error occurs. But after about 20 minutes, all the bugs will be fixed automatically and I can run the code again. But unfortunately I get the same error message again. Please help.
The code in the question has several issues. I will only explicitly mention some issues related to use of classes in System.Data.SqlClient, and not mention general issues, though the code shown here solves many of the general issues, but not all.
The classes SqlConnection, SqlCommand, SqlDataAdapter, SqlDataReader and so on, are lightweight, and should be created and released in the innermost scope possible. There is nothing to gain by trying to reuse these by holding on to them across queries. They also need to be properly managed with regards to memory use as well as resource use, not only when execution follows the success path, but also when errors arise. This can be achieved as follows.
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public static class FirstClass
{
private static string connectionString =
ConfigurationManager.ConnectionStrings["WebSiteConnectionString"].ConnectionString;
private static SqlConnection GetConnection()
{
return new SqlConnection(connectionString);
}
public static DataTable DbSelect(string sql)
{
using (var con = GetConnection())
{
using (var cmd = new SqlCommand(sql, con))
{
using (var adapter = new SqlDataAdapter(cmd))
{
try
{
DataTable result = new DataTable();
adapter.Fill(result);
return result;
}
catch
{
return null;
}
}
}
}
}
public static void ExeSp(string spName)
{
using (var con = GetConnection())
{
using (var cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = spName;
cmd.ExecuteNonQuery();
}
}
}
public static void ExeSqlCmd(string sql)
{
using (var con = GetConnection())
{
using (var cmd = new SqlCommand(sql, con))
{
try
{
cmd.ExecuteNonQuery();
}
catch
{
}
}
}
}
}
The class has been made static, which makes sure all memory and resource management now takes place within each single method. We no longer rely on knowing how the class itself is used elsewhere in order to understand how things work. Within the methods, use of using now clearly tells us how resources, including memory, is allocated and deallocated. We can see that everything is properly disposed, so that there is no longer any way that any resource can be lying around between database calls, whether there's success or error in calls. In the DbSelect method, the DataTable is created as close to its point of use as possible, so that we easily see what it's doing.
It is not clear what the intention of having one local and one class level DataTable was in the original code, which returns one or the other - likely just a temporary glitch while experimenting - but in this new version the caller is responsible for disposing the returned result after use. An alternative is possibly to have the caller offer a DataTable to fill in, if that's easier for the caller. If so, just clear the table before filling.
When it comes to error handling, it can be improved, but I won't go into that.
This code compiles, but I have not verified that it actually works. My intention is to show how to organize these kinds of database calls in general, and you can work on fixing any error I may have overlooked from there on.
I have been trying to search for this and could not find an answer, May be I was not looking at the right places so please bear with me...
Question:
I know that a using statement calls the dispose method of the object, for example:
using (SqlConnection conn = new SqlConnection(conString))
{
// some work
}
// dispose method for this connection object will be called must.
But what happens to the objects created inside this using statement?
using (SqlConnection conn = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query, conn);
// some work
}
Will the dispose method of command object be also called? Or should I do this instead:
using (SqlConnection conn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
//some work
}
// some work
}
Which is the best practice and which one will be more efficient ?
Will the dispose method of command object be also called?
No
Or should I do this instead:
Yes
Which is the best practice and which one will be more efficient ?
The one that works - the last one. Note you can avoid "heading right" on the page:
using (SqlConnection conn = new SqlConnection(conString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
// some work
}
I'm too lazy to use ADO.NET directly; another option is to get a tool to handle everything except the connection (example shown is "dapper", but other tools exist):
using (SqlConnection conn = new SqlConnection(conString))
{
var data = conn.Query<SomeType>(someSql, new { foo, bar }).ToList();
// where #foo and #bar are parameters in the sql
}
then you don't need to worry about the command, data-reader, parameters, etc.
Yes you should use the second. also you can shorten that statement to:
using (SqlConnection conn = new SqlConnection(conString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
//some work
}
// some work
If you don't wrap your disposable object with a using statement the Dispose method will not be called.In your case only the connection will be disposed.
I know that a using statement calls the dispose method of the object, for example:
If that object implements the IDisposable interface. Otherwise, you can't even use an object in a using statement.
You should use a using statement for each object you want to dispose of after some operations. So you should use the last example you provided yourself (with the two using statements).
i am creating a connection to my database from from visual studio.
this is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class CM : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("server =KIRITI; database =msdb; Integrated Security=True");
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
String NotesMaker = TextBox1.Text;
SqlCommand cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values('"+NotesMaker+"',con)");
cmd.ExecuteNonQuery();
cmd.CommandText = "Select##Identity";
con.Close();
}
}
I get an error at command.Executenonquery(): An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: ExecuteNonQuery: Connection property has not been initialized.
Please help!! I'm blocked from two days!!
Thats the first place where I have seen string concatenation causing conn to be part of query.
You misplaced string quotes, your statement should be:
SqlCommand cmd =
new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values('" + NotesMaker + "'",con);
In your current code, you are passing string "Insert into NOTESMAKER(NOTESMAKER) Values('"+NotesMaker+"',con)", hence the connection property is not initialized and hence the exception.
You should never use string concatenation for creating queries, instead use Parameters. This will save you from SQL Injection. Like:
using(SqlConnection con = new SqlConnection("connectionstring"))
using(SqlCommand cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values(#NotesMaker)",con))
{
cmd.Parameters.AddWithValue("#NotesMaker", NotesMaker);
con.Open();
cmd.ExecuteNonQuery();
}
You put con inside the quotes of the first parameter of the constructor for SqlCommand, thus the code is complaining because you aren't setting the Connection property of your SqlCommand
change
SqlCommand cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values('"+NotesMaker+"',con)");
to
SqlCommand cmd = new SqlCommand("Insert into NOTESMAKER(NOTESMAKER) Values('"+NotesMaker+"')",con);
When I try to write in C# a connection to my app to my database, I build the application successfully in Visual Studio 2005 but when I run the site in debugger i get an error:
Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 118.
Here is the connection code that is giving the error:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Server"].ConnectionString);
I have the connection string written correctly in my web.config, file so im clueless on what this remotely means. Im not sure if im missing anything. Any help appreciated. Here is my entire code for the section that might help:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
public partial class RateAnalyzerPage: System.Web.UI.Page
{
protected void Search_Click(object sender, EventArgs e)
{
string IDnumber = mechantNumber.Text;
string selectSQL = "SELECT FROM Authors Where MID='"+ IDnumber +"'";
// SqlConnection con = new SqlConnection(#"Server=");
//SqlConnection con = new SqlConnection();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Server"].ConnectionString);
SqlDataReader reader;
try
{
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
reader = cmd.ExecuteReader();
while (reader.Read())
{
QualVol.Text = reader["TotalVolume"].ToString();
}
reader.Close();
}
catch (Exception err)
{
}
finally
{
con.Close();
}
}
}
Let me know if im missing some data that would help.
Heres the connection string:
I've separated out and XML decoded the connection string value:
Data Source=Server;Initial Catalog=Odata;Integrated Security=True;MultipleActiveResultSets=False;Packet Size=4096;Application Name="Microsoft SQL Server Management Studio"User ID=Name;Password=PW
As you can see, you're missing a ; between Application Name and User ID. I'm not sure if that's the issue, but it's possible.
Your connection string use the Integrated Security=True, but the right syntax is
Integrated Security=SSPI; or Trusted_Connection=True so change it and remove the UserId and Password.
(or remove Integrated Security=True and leave UserID and Password)
Try to change something in your code.
protected void Search_Click(object sender, EventArgs e)
{
string IDnumber = mechantNumber.Text;
string selectSQL = "SELECT * FROM Authors Where MID=#num";
using(SqlConnection con = new SqlConnection
(System.Configuration.ConfigurationManager.ConnectionStrings
["Server"].ConnectionString))
{
SqlDataReader reader;
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#num", IDNumber);
reader = cmd.ExecuteReader();
while (reader.Read())
{
QualVol.Text = reader["TotalVolume"].ToString();
}
reader.Close();
}
}
Try to use the using statemend, this guarantees the disposing of your connection
Try to use parametrized query, this avoid Sql Injection attacks and quoting problems
Also SELECT requires a fields list or *
I think Jacob has it right. On a side note, don't do this:
string selectSQL = "SELECT FROM Authors Where MID='"+ IDnumber +"'";
This will lead to sql injection attacks, just like the one that was used to get yahoo user accounts last week.
Do this instead:
string selectSQL = "SELECT * FROM Authors Where MID=#ID";
cmd.Parameters.AddWithValue("#ID", IDnumber );
I am trying to write t-sql in C# (visual studio). I have this code to connect to the database:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Xtreme\\Desktop\\CardsDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
Where/how do I write the T-SQL code and how do I get the result?
Can someone give me an simple select example in my code?
You can use DataAdapter.Fill Method:
try
{
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM Employee", cnn))
{
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t; //if you want.
}
}
catch (Exception ex)
{
MessageBox.Show("Problem!");
}
Create a SqlCommand and set the CommandType to CommandType.Text. Then add your SQL to the CommandText property of the SqlCommand.
SqlCommand command = new SqlCommand(commandName, (SqlConnection)Connection);
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM MyTable";
IDataReader result = command.ExecuteReader();
Ardman already showed you how to execute any arbitary sql command. But what i didn't answer very well, is where to put your sql statement.
I think it is a very bad behaviour and also not very good to read if you put your statement directly into the code.
A better method (in my eyes) is the following:
Within your project create a new folder (maybe called Queries)
Right click this folder and select Add - New Item
In the dialog just select Textfile and give it the name about what this query will do
Make sure you replace the file extension from .txt to .sql
Just put your statement right into this file
In the Resource Editor add this file as a resource
Now you can access this sql statement within your project just by using Properties.Resources.MySqlStatement