ExecuteNonQuery: Connection property not initialized - c#

How do i resolve ExecuteNonQuery: Connection property is not initialized. I already made my cmd.Connection = con; this is my code please help
Private void button1_Click(object sender, EventArgs e)
{
if (img_file != null)
{
FileStream fs = new FileStream(img_file, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[]image = new byte[fs.Length];
fs.Read(image,0,Convert.ToString(fs.Length));
fs.Close();
SqlCommand cmd = new SqlCommand("INSERT INTO member_details (name,address,email,phone_number,picture) VALUES('"+textBox1.Text+"', '"+textBox2.Text+"', '"+textBox3.Text+"', #pic)", con);
SqlParameter prm = new SqlParameter("#pic", SqlDbType.VarBinary, image.Length, ParameterDirection.Input, false, 0,0, null, DataRowVersion.Current, image);
cmd.Parameters.Add(prm);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
}

You can use below code as reference to fix your code:
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statemnt Here";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
You can simply initialize and close connections by
using(SqlConnection con = new SqlConnection(connectionstring))
{
--write all your command n execution code here---;
}
Apart from this, one suggestion, you need to use parameterized query or Stored Proc with paramerts to avoid SQLInjection:
Reference to SQLInjection : https://www.veracode.com/security/sql-injection

Related

C# SqlDataAdapter Must declare the scalar variable Sql Exception

New to C# and working on a Windows Form application. I am attempting to execute an update query against a SQL database, but keep running into "Must declare the scalar variable" error and I do not understand why.
The below code successfully opens the connection. My update statement is valid. Looking through a lot of posts on this topic and I am just not seeing my error... any help would be appreciated.
public void SetJobStatus(long JobId)
{
string strSql = "update Jobmaster set jobstatus = 5 where equid = #stationId AND ID <> #jobId AND OfflineEntry = 0;";
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = GlobalVars.connString;
conn.Open();
// use the connection here, and check to confirm it is open
if (conn.State != ConnectionState.Open)
{
if (conn != null)
{
conn.Close();
}
conn.Open();
}
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
command = new SqlCommand(strSql, conn);
//below AddWithValue gives error:
//System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#stationId".'
//command.Parameters.AddWithValue("#stationId", 1);
//command.Parameters.AddWithValue("#jobId", JobId);
//next I tried this, and the same error:
//System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#stationId".'
command.Parameters.Add("#stationId", SqlDbType.Int);
command.Parameters["#stationId"].Value = 1;
command.Parameters.Add("#jobId", SqlDbType.Int);
command.Parameters["#jobId"].Value = JobId;
adapter.UpdateCommand = new SqlCommand(strSql, conn);
adapter.UpdateCommand.ExecuteNonQuery();
}
}
I have checked your code and it's required some changes. Please try to run below code:
public void SetJobStatus(int JobId)
{
string strSql = "update Jobmaster set jobstatus = 5 where equid = #stationId AND ID <> #jobId AND OfflineEntry = 0;";
using (SqlConnection conn = new SqlConnection())
{
try
{
conn.ConnectionString = GlobalVars.connString;
conn.Open();
SqlCommand command = new SqlCommand(strSql, conn);
command.CommandType = CommandType.Text;
command.Parameters.Add("#stationId", SqlDbType.Int);
command.Parameters["#stationId"].Value = 1;
command.Parameters.Add("#jobId", SqlDbType.Int);
command.Parameters["#jobId"].Value = JobId;
command.ExecuteNonQuery();
}
catch (Exception ex)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}
Tips:
Always close connection after completion of task or in case of error.
Thanks to everyone who chimed in here. WSC's comment did the trick- changing adapter.UpdateCommand = command; worked. I tried three variations of adding parameters after making WSC's change- two of them worked, one did not.
My revised code is below. I have all three variations listed in the code- hopefully this will help somebody else out.
public void SetJobStatus(long JobId)
{
string strSql = "update Jobmaster set jobstatus = 5 where equid = #stationId AND ID <> #jobId AND OfflineEntry = 0;";
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = GlobalVars.connString;
conn.Open();
// use the connection here, and check to confirm it is open
if (conn.State != ConnectionState.Open)
{
if (conn != null)
{
conn.Close();
}
conn.Open();
}
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
command = new SqlCommand(strSql, conn);
//works
command.Parameters.AddWithValue("#stationId", GlobalVars.stationId);
command.Parameters.AddWithValue("#jobId", JobId);
//works
//command.Parameters.Add("#stationId", SqlDbType.Int);
//command.Parameters["#stationId"].Value = 5;
//command.Parameters.Add("#jobId", SqlDbType.Int);
//command.Parameters["#jobId"].Value = JobId;
//throws error at adapter.UpdateCommand.ExecuteNonQuery line:
//'The parameterized query '(#stationId int,#jobId int)update Jobmaster set jobstatus = 5 wh' expects the parameter '#stationId', which was not supplied.'
//command.Parameters.Add("#stationId", SqlDbType.Int, 5);
//command.Parameters.Add("#jobId", SqlDbType.Int, (int)JobId);
adapter.UpdateCommand = command;
adapter.UpdateCommand.ExecuteNonQuery();
}
}

updating sql server database using c# in asp.net

There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?
protected void Page_Load(object sender, EventArgs e) {
rno.Text = Request.QueryString["rno"];//rno is a textbox
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "select fname from table1 where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if (reader.Read()) {
fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
}
reader.Close();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
protected void modify_Click(object sender, EventArgs e) {
fName.ReadOnly = false;
}
protected void savechanges_Click(object sender, EventArgs e) {
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update table1 set fname=#fname where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", sfname);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
I have tried your code which executed fine and updated database table as well.
I have tried like below :
string connectionString = #"data source=MS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update TestTable set fname=#fname where rno =rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", "Test");
command.Parameters.AddWithValue("#rno", "rno");
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
Another way I have tried.
using (SqlConnection connection = new SqlConnection(connectionString ))
{
connection.Open();
var queryText = "UPDATE TestTable SET fname = '" + requestPram.fname + "' WHERE rno ='" + requestPram.rno + "'";
using (SqlCommand cmd = new SqlCommand(queryText, connection))
{
responseResults = await cmd.ExecuteNonQueryAsync();
}
connection.Close();
}
Hope it would help
After searching for a while, I found out that this code was executing perfectly. The only problem was that everything was inside the page_Load() method and thus the page was reloading everytime I updated the database and thus removing the small window to edit the textboxes. The appropriate solution was to associate this code with some button event rather than with the page_Load() event.

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();
}
}
}

Error in server 'executenonquery requires an open and available connection'

I got this error on server not in local and when facing this error, then i re-upload that related class file. after doing this problem solved but not permanently.
Error:
executenonquery requires an open and available connection. The
connection's current state is open.
Code:
int n;
try
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = DataConnection.Con;
cmd.CommandText = "sp_InsertUpdateDeleteValidationDate";
cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 0;
cmd.Parameters.AddWithValue("#Task", "CheckExist");
cmd.Parameters.AddWithValue("#id", 0);
cmd.Parameters.AddWithValue("#AdId", "");
cmd.Parameters.AddWithValue("#Username", "");
cmd.Parameters.AddWithValue("#DOE", DOE);
cmd.Parameters.AddWithValue("#ExpieryDate", DateTime.Now);
cmd.Parameters.AddWithValue("#DOR", DateTime.Now);
cmd.Parameters.Add("#flag", SqlDbType.Int).Direction = ParameterDirection.Output;
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
cmd.ExecuteNonQuery();
n = Convert.ToInt32(cmd.Parameters["#flag"].Value);
return n;
}
}
catch (SqlException Ex)
{
return 0;
}
You only create one connection in your DataConnection class. You should create a new connection for each database call and let the driver's connection pooling take care of efficiently reusing them.
change your DataConnection class to this:
public class DataConnection
{
public static SqlConnection Con
{
get
{
return new SqlConnection(ConfigurationManager
.ConnectionStrings["conn"].ConnectionString);
}
}
}
and use a using statement when you use the connection like in ekad's answer:
using (SqlConnection conn = DataConnection.Con)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
//use the command here
}
}
Looks like your SqlConnection is never closed. Try to use using statement to make sure that the SqlConnection is closed after executing cmd.ExecuteNonQuery()
int n;
try
{
using (SqlConnection conn = DataConnection.Con)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "sp_InsertUpdateDeleteValidationDate";
cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 0;
cmd.Parameters.AddWithValue("#Task", "CheckExist");
cmd.Parameters.AddWithValue("#id", 0);
cmd.Parameters.AddWithValue("#AdId", "");
cmd.Parameters.AddWithValue("#Username", "");
cmd.Parameters.AddWithValue("#DOE", DOE);
cmd.Parameters.AddWithValue("#ExpieryDate", DateTime.Now);
cmd.Parameters.AddWithValue("#DOR", DateTime.Now);
cmd.Parameters.Add("#flag", SqlDbType.Int).Direction = ParameterDirection.Output;
conn.Open();
cmd.ExecuteNonQuery();
n = Convert.ToInt32(cmd.Parameters["#flag"].Value);
return n;
}
}
}
catch (SqlException Ex)
{
return 0;
}

Categories

Resources