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();
}
Related
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.
SqlConnection conn = new SqlConnection(#"Data Source=SAI\SQLEXPRESS;Initial Catalog=testing;Integrated Security=True;Pooling=False");
conn.Open();
SqlCommand command = new SqlCommand();
string test = "UPDATE attend Year='2014' WHERE Id = '2'";
command = new SqlCommand(test, conn);
command.ExecuteNonQuery();
conn.Close();
Year and id are both varchar. Error is:
Incorrect syntax near 'Year'.
Should be :
UPDATE attend SET Year='2014' WHERE Id = '2'
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();
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.
I'm having problem with my sql query.
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLExpress;" + "Trusted_Connection=True;" + "User Instance=True;" + "AttachDbFilename=|DataDirectory|\\fbi.mdf;";
string sqlQuery4 = "SELECT Car FROM tbl1 JOIN tbl2 ON (tbl1.userID = tbl2.userID) WHERE tbl2.username='Bob'";
SqlCommand cmd4 = new SqlCommand(sqlQuery4, conn);
conn.Open();
SqlDataReader rd = cmd4.ExecuteReader();
rd.Read();
ddl1.Items.Add(rd.GetValue(0).ToString());
conn.Close();
So it should return all cars from tbl1 that belongs to Bob. Query only return one string and put it into Listbox "ddl1" while it should return at least 3 of them.
Any ideas?
You need to loop through the reader:
while (rd.Read()){
ddl1.Items.Add(rd.GetValue(0).ToString());
}
Novak, not sure what your issue was with Curt's solution, as it is correct. Your complete statement should look like:
string connectionString= "Data Source=.\\SQLExpress;Trusted_Connection=True;User Instance=True;AttachDbFilename=|DataDirectory|\\fbi.mdf;";
string query = "SELECT Car FROM tbl1 JOIN tbl2 ON (tbl1.userID = tbl2.userID) WHERE tbl2.username='Bob'";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
ddl1.Items.Add(reader.GetValue(0).ToString());
}
}
}
}
try below code:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLExpress;" + "Trusted_Connection=True;" + "User Instance=True;" + "AttachDbFilename=|DataDirectory|\\fbi.mdf;";
string sqlQuery4 = "SELECT Car FROM tbl1 JOIN tbl2 ON (tbl1.userID = tbl2.userID) WHERE tbl2.username='Bob'";
SqlCommand cmd4 = new SqlCommand(sqlQuery4, conn);
conn.Open();
SqlDataReader rd = cmd4.ExecuteReader();
ddl1.DataSource = rd;
ddl1..DataTextField = "columnname"; //your column name
ddl1.DataValueField = "columnname";
ddl1.DataBind();
rd.Close();
conn.Close();