SqlConnection cn = new SqlConnection(#"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******");
SqlCommand cmd = new SqlCommand();
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=#finish where Name='" + Name + "'";
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.ExecuteNonQuery();
cmd.Clone();
The error message
Executenonquery connection property has not been initialized.
the problem with your current code is that you have not set the Connection property of the SqlCommand object. Try this,
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
and you must also parameterized the values set on the name
String Name = Request.QueryString["Name"];
cmd.CommandText = "UPDATE navaznost_ukolu SET finish=#finish where Name=#name";
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.Parameters.Add(new SqlParameter("#name", Name));
FULL CODE
string finish = DropDownListFi.SelectedValue;
String Name = Request.QueryString["Name"];
string connStr = #"DataSource=dbedu.cs.vsb.cz\SQLDB;
Persist Security Info=True;
User ID=*****;
Password=*******";
string sqlStatement = #"UPDATE navaznost_ukolu
SET finish = #finish
WHERE Name = #Name";
using (SqlConnection conn = new SqlConnection(connStr))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sqlStatement;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlParameter("#finish", finish));
cmd.Parameters.Add(new SqlParameter("#name", Name));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch(SqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}
For proper coding
use using statement for propr object disposal
use try-catch block to properly handle objects
The error is self-explanatory, you have not assigned the connection to the command. You can use the constructor:
using(var cn = new SqlConnection(#"DataSource=dbedu.cs.vsb.cz\SQLDB;Persist Security Info=True;User ID=*****;Password=*******"))
using(var cmd = new SqlCommand(
"UPDATE navaznost_ukolu SET finish=#finish where Name=#Name"
, cn))
{
string finish = DropDownListFi.SelectedValue;
cn.Open();
String Name = Request.QueryString["Name"];
cmd.Parameters.AddWithValue("#finish", finish);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.ExecuteNonQuery();
}
Note that i've also used a sql-parameter for the Name and using statements to ensure that anything implementing IDisposable gets disposed, even in case of an exception. This will also close the connection.
Related
I am writing the following lines of code to update the data in access database.
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = #password where userId = #userId;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#userId", authResult.UserId);
cmd.Parameters.AddWithValue("#password", newPassword);
cmd.ExecuteNonQuery();
}
}
When this line runs cmd.ExecuteNonQuery(); I got the following error:
Syntax error in UPDATE statement
Am I missing anything?
Update - 2
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = String.Format(Queries.dbConnection, databasePath);
con.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set password = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("p1", OleDbType.VarChar, 100).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}
}
First of all: MS Access / OleDB does not used named parameters - but positional parameters. So the order in which you specify the parameters is very much relevant!
Second: OleDB uses the ? as a parameter placeholder.
So try this code:
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "update tblusers set [password] = ? where userId = ?;";
cmd.CommandType = System.Data.CommandType.Text;
// parameters - do *NOT* use "AddWithValue", and specify in the *correct order*!
// since the parameters are *positional*, the name provided is irrelevant
cmd.Parameters.Add("p1", OleDbType.VarChar, 50).Value = newPassword;
cmd.Parameters.Add("p2", OleDbType.Integer).Value = authResult.UserId;
cmd.ExecuteNonQuery();
}
For reference, this page (add.ashx.cs), is an add page to a database.
What I'm trying to do is :
figure out how to execute string queryID, and then
store the results of queryID
I'm a bit new at this, but this is what I'm working with so far. Am I on the right path, and what should I change? I don't believe the code below includes storing the results, but just executing queryID.
// new query to get last ID value
// store the command.executeNonQuery results into a variable
string queryID = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
// first: look up how to execute queryID
// then: store results of query ^
// execute queryID? (section below)
SqlConnection sqlConnection1 = new SqlConnection(queryID);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "Select * FROM queryID";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// data is accessible through the datareader object here
sqlConnection1.Close();
There are some things missmatched in your code sample. First queryID is your actual query. Second in SqlConnection you need to provide a connection string, that connects to your database (SQL Server, ACCESS, ...). A valid example could look like this:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
SqlDataReader reader;
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
List<string> results = new List<string>();
if(reader.HasRows)
{
while(reader.Read())
{
results.Add(reader[0].ToString());
}
}
sqlConnection1.Close();
Another thing is, that you execute a reader but only select one single value. You can perfectly use ExecuteScalar for that:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
SqlConnection sqlConnection1 = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
sqlConnection1.Close();
One last thing. You should use objects that implement IDisposable in a using block. This way the will be removed from memory when they are no longer needed:
// this is just a sample. You need to adjust it to your needs
string connectionStr = "Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=SSPI;";
using(SqlConnection sqlConnection1 = new SqlConnection(connectionStr))
{
SqlCommand cmd = new SqlCommand(sqlConnection1 );
cmd.CommandText = "SELECT TOP (1) IDENT_CURRENT('dbo.license_info') FROM dbo.license_info";
cmd.CommandType = CommandType.Text;
sqlConnection1.Open();
string result = cmd.ExecuteScalar().ToString();
}
I got error "System.Runtime.InteropServices.InvalidComObjectException: 'COM object that has been separated from its underlying RCW cannot be used.'" ONLY when i execute OleDbCommand object in using block with parameters
using (OleDbCommand comm = new OleDbCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
string txt = "SELECT* FROM [ListForGroup] WHERE [email] = #email";
comm.Parameters.Add("#email", OleDbType.VarWChar).Value = userEmail;
comm.CommandText = txt;
conn.Open();
OleDbDataReader reader = comm.ExecuteReader();
List<ListForGroups> list = returnLists(reader);
conn.Close();
cmbSelectList.DataSource = list;
cmbSelectList.DisplayMember = "listName";
cmbSelectList.ValueMember = "listForGroupsID";
}
Does anyone know reason for that. I can resolve it to use OleDbCommand object with CommandText without parameters but i read that's bad idea. And i want to do it in using block to be sure that all reasources will be released.
I resolved this problem
using (OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand comm = new OleDbCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
string txt = "SELECT* FROM [ListForGroup] WHERE [email] = #email";
comm.Parameters.Add("#email", OleDbType.VarWChar).Value = userEmail;
comm.CommandText = txt;
conn.Open();
OleDbDataReader reader = comm.ExecuteReader();
List<ListForGroups> list = returnLists(reader);
cmbSelectList.DataSource = list;
cmbSelectList.DisplayMember = "listName";
cmbSelectList.ValueMember = "listForGroupsID";
}
I don't know why I didn't create OleDbConnection in brackets next to using. Another when to resolve it is to close connection after using block.
I am using asp.net with c# and there exist an error in these line of codes.
protected void btnsubmit_Click(object sender, EventArgs e)
{
string type = "c";
string FID = Session["FID"].ToString();
SqlConnection cn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
//int str_diff = Convert.ToInt32(ConfigurationManager.AppSettings["Difference"]);
cn.ConnectionString = #"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True";
cn.Open();
cmd.CommandText = "update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60";
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect("~/Faculty/Personaldet.aspx");
}
You haven't set the connection to the command
cmd.Connection = cn;
You need to assign the SqlConnection to the SqlCommand. As an additional suggestion I would wrap the connection in a using block to ensure it is correctly disposed in the case of an exception.
using (SqlConnection cn = new SqlConnection(#"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True")
{
cn.Open();
SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();
}
SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();
This should be a simple solution but Visual Studio 2012 give me errors that say sqlCon is a field but is used like a type and the same error for Textbox1... Maybe I am missing an assembly reference or proper connection imports? I'm looking to continue this simple route.
MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;");
MySqlCommand commandText = new MySqlCommand ("SELECT count(Dues) From Students");
sqlCon.CommandText = "SELECT * count(Dues) FROM Students";
sqlCon.Connection = sqlCon;
TextBox1.Text = sqlCon.ExecuteScalar().ToString();
Open the connection
use using statements
use Try-catch block
Snippet,
string connStr = "Server=***;Port=***;Database=***;Uid=***;Pwd=***;";
string query = "SELECT count(Dues) From Students";
using(MySqlConnection sqlCon = new MySqlConnection(connStr))
{
using(MySqlCommand sqlComm = new MySqlCommand())
{
sqlComm.Connection = sqlCon;
sqlComm.CommandText = query;
try
{
sqlCon.Open();
TextBox1.Text = sqlComm.ExecuteScalar().ToString();
}
catch(MySqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;");
MySqlCommand commandText = new MySqlCommand ("SELECT count(Dues) From Students");
//sqlCon is of type MySqlConnection which is derived from DbConnection
sqlCon.CommandText = "SELECT * count(Dues) FROM Students";
//sqlCon has no Connection property, and why are you even assigning sqlCon to that property
sqlCon.Connection = sqlCon;
//ofcourse this will fail
TextBox1.Text = sqlCon.ExecuteScalar().ToString();
I believe what you're trying to achieve is:
MySqlConnection sqlCon = new MySqlConnection("Server=***;Port=***;Database=***;Uid=***;Pwd=***;");
MySqlCommand command = new MySqlCommand ("SELECT count(Dues) From Students");
try
{
sqlCon.Open();
command.Connection = sqlCon;
TextBox1.Text = command.ExecuteScalar().ToString();
}
finally
{
sqlCon.Close();
}