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();
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();
}
I connected my oracle database to visual studio and now I'm trying to execute procedure I created in my database.
I tried this:
OracleCommand cmd = new OracleCommand("BEGIN ADD_USER('"+txtName.Text+"','"+txtName2.Text+"',"+txtID.Text+"); END;" );
cmd.ExecuteNonQuery();
My procedure has 3 parameters : name, 2name, id. It works fine when I use this command in sqldeveloper, but I get error when I try it in my project.
using (OracleConnection cn = new OracleConnection("con string"))
{
cn.Open();
OracleCommand cmd = new OracleCommand("ADD_USER");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cn;
cmd.Parameters.Add("YourSPParamName1", OracleDbType.{YourFieldTypeInDB}).Value = txtName.Text;
cmd.Parameters.Add("YourSPParamName2", OracleDbType.{YourFieldTypeInDB}).Value = txtName2.Text;
cmd.Parameters.Add("YourSPParamName3", OracleDbType.{YourFieldTypeInDB}).Value = txtID.Text;
cmd.ExecuteNonQuery();
}
Something like this should work.
Here's how It works for me:
OracleConnectionStringBuilder sb = new OracleConnectionStringBuilder();
sb.DataSource = "localhost";
sb.UserID = "something";
sb.Password = "pass";
OracleConnection conn = new OracleConnection(sb.ToString());
conn.Open();
OracleCommand cmd = new OracleCommand("ADD_USER");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.Parameters.Add("NAME", OracleDbType.Varchar2).Value = txtName.Text;
cmd.Parameters.Add("NAME2", OracleDbType.Varchar2).Value = txtName2.Text;
cmd.Parameters.Add("ID", OracleDbType.Int32).Value = txtID.Text;
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.
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();
}
I am new to C# and trying to populate a DropDownList based on a database value. I tried connecting to database as shown below - tested with the statement and it says connected. Can I assume this is correct? Am I on the right track? Also, how do I then select value from the table and fill DropDownList with a field?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
connection.Open();
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
SqlDataReader dReader;
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="Select distinct [Name] from [Names]" +
" order by [Name] asc";
connection.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
//Names collection is a combo box.
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close()
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
Hope that helps................
It's So Much Simple :----
SqlConnection con = new SqlConnection();
DataSet ds = new DataSet();
con.ConnectionString = #"Data Source=TOP7\SQLEXPRESS;Initial Catalog=t1;Persist Security Info=True;User ID=Test;Password=t123";
string query = "Select * from tbl_User";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
con.Open();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(ds);
comboBox1.Items.Clear();
comboBox1.DisplayMember = "UserName";
comboBox1.ValueMember = "UserId";
comboBox1.DataSource = ds.Tables[0];
------------------------------------------------------------------------
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}