My code gets to conn.Open and gives me "Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll"
Here is the block of code:
_timer.Stop();
string path = #"C:\testlog.log";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDB_Conn"].ConnectionString);
string query = "SELECT RawImportEnabled, ImportDayTimeStamp from Settings";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open(); // Dies here
SqlDataReader rdr = cmd.ExecuteReader();
Order is missing ...first open connection then use sql command
_timer.Stop();
string path = #"C:\testlog.log";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDB_Conn"].ConnectionString);
conn.Open(); // sholud be here
string query = "SELECT RawImportEnabled, ImportDayTimeStamp from Settings";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader rdr = cmd.ExecuteReader();
Besides your code is not formatted either..Format like this
string path = #"C:\testlog.log";
String connectionString = ConfigurationManager.ConnectionStrings["MYDB_Conn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open(); // sholud be here
string query = "SELECT RawImportEnabled, ImportDayTimeStamp from Settings";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
String RawImportEnabled = Convert.ToString(reader["RawImportEnabled"]);
//Do some thing
}
}
This has some benefits like debugging the connection string by putting a breakpoints ,Disposal of connection without worrying for using statements etc
_timer.Stop();
string path = #"C:\testlog.log";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDB_Conn"].ConnectionString);
string query = "SELECT RawImportEnabled, ImportDayTimeStamp from Settings";
conn.Open(); // Dies here again.
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
Related
I'm trying to prevent SQL injections. Am I doing this right? (I'm using MS Access.) Should I still use sqlparameter?
OleDbParameter[] myparm = new OleDbParameter[2];
myparm[0] = new OleDbParameter("#UserID", UserName.Text);
myparm[1] = new OleDbParameter("#Password", encode);
string queryStr = "SELECT * FROM TMUser WHERE UserID=#UserID AND Password=#Password";
OleDbConnection conn = new OleDbConnection(_connStr);
OleDbCommand cmd = new OleDbCommand(queryStr, conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
Close!
string queryStr = "SELECT * FROM TMUser WHERE UserID=#UserID AND Password=#Password";
OleDbConnection conn = new OleDbConnection(_connStr);
OleDbCommand cmd = new OleDbCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#UserID", UserName.Text);
cmd.Parameters.AddWithValue("#Password", encode);
The parameters are part of the command object and you use the Parameters.AddWithValue method to set the parameter values to what you have defined in the query string.
By the way, you should be using using statements to encapsulate some of your objects, here is what I typically do:
using (OleDbConnection conn = new OleDbConnection(_connStr))
using (OleDbCommand = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT ...";
cmd.Parameters.AddWithValue(...);
cmd.ExecuteReader();
//...
}
That way you don't have to worry about cleaning up resources if something goes wrong inside or closing the connection when you are done.
I keep getting this error
There is already an open datareader associated with this command which must be closed first.
at this line of code:
using (SqlDataReader rd = command.ExecuteReader())
I have tried to close all other SqlDataReader's in class but it didn't work.
public int SifreGetir(string pEmail) {
SqlCommand command = con.CreateCommand();
command.CommandText = #"SELECT Sifre FROM Kullanici WITH (NOLOCK) WHERE email=#email";
command.Parameters.Add("#email", SqlDbType.VarChar);
command.Parameters["#email"].Value = pEmail;
using (SqlDataReader rd = command.ExecuteReader())
{
rd.Read();
string pass = rd["Sifre"].ToString();
int p = Convert.ToInt32(pass);
return p;
}
}
Try implementing your code in the below format
using(SqlConnection connection = new SqlConnection("connection string"))
{
connection.Open();
using(SqlCommand cmd = new SqlCommand("your sql command", connection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
//do something
}
}
}
}
}
The using statement will ensure disposal of the objects at the end of the using block
try this:
public int SifreGetir(string pEmail) {
SqlConnection con = new SqlConnection("Your connection string here");
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
SqlCommand command = new SqlCommand(#"SELECT Sifre FROM Kullanici WITH (NOLOCK) WHERE email=#email",con);
command.CommandType = CommandType.Text;
command.Parameters.Add("#email", SqlDbType.VarChar).Value = pEmail;
da.Fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
string pass = dr["Sifre"].ToString();
int p = Convert.ToInt32(pass);
return p;
}
con.Close();
}
You have used Using Keyword for SQL Reader but There is nothing to take care of your command and connection object to dispose them properly. I would suggest to try disposing your Connection and command both objects by Using keyword.
string connString = "Data Source=localhost;Integrated " + "Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new;
cmd.CommandText = "SELECT ID, Name FROM Customers";
conn.Open();
using (SqlDataReader rd = command.ExecuteReader())
{
rd.Read();
string pass = rd["Sifre"].ToString();
int p = Convert.ToInt32(pass);
return p;
}
}
I am trying to connect to an oracle database using C#.
Here is my code:
OracleConnection conn = new OracleConnection(); // C#
conn.ConnectionString = oradb;
conn.Open();
string sql = " select department_name from departments where department_id = 10"; // C#
OracleCommand cmd = new OracleCommand();
cmd.CommandText = sql;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text; ///this is the line that gives the error
What is the proper way to set the command type? Thank you.
Using Store Procedure:
using (OracleConnection conn = new OracleConnection( oradb ))
{
conn.Open();
OracleCommand cmd = new OracleCommand("StoreProcedureName", con);
cmd.CommandType = CommandType.StoredProcedure;
//specify command parameters
//and Direction
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//string s = reader.GetInt32(0) + ", " + reader.GetInt32(1);
}
}
}
CommandType.Text: (not mandatory to specify CommandType).
using (OracleConnection conn = new OracleConnection( oradb ))
{
string sql = #"SELECT department_name FROM departments
WHERE department_id = #department_id";
conn.Open();
OracleCommand cmd = new OracleCommand(sql, conn);
//specify command parameters
cmd.Parameters.Add(new OracleParameter("#department_id", 10));
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//string s = reader.GetString(0);
}
}
}
Make sure you toss each of these pieces in a using() statement, i.e.
using( OracleConnection conn = new OracleConnection( oradb ) )
{
conn.Open();
using( OracleCommand cmd = new OracleCommand( "sql here", conn ) )
{
//cmd.Execute(); cmd.ExecuteNonQuery();
}
}
We use oracle database connection and our class database access does not have a dispose or close. It interferes with something or performance of the application? I saw this example:
string oradb = "Data Source=ORCL;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from departments";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
label1.Text = dr.GetString(0);
conn.Dispose();
And I realized that it opens the connection and then kills her. This is correct? Is there any other better?
I'm leaving my connection open and then ends up being closed for a while. I think that's it. This so wrong?
Use the Using statement with disposable objects. In particular with any kind of connection and datareaders
string oradb = "Data Source=ORCL;User Id=hr;Password=hr;";
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select * from departments";
cmd.CommandType = CommandType.Text;
using(OracleDataReader dr = cmd.ExecuteReader())
{
dr.Read();
label1.Text = dr.GetString(0);
}
}
Here you could read about the Using statement and why it is important. Regarding the connection and readers, you should enclose the objects with the using statement to be sure that everything is properly closed and disposed when you exit from the using block ALSO in case of exceptions
I am trying to take a single value from a database, but the cycle does not seem to start at all?
if (connection.State == ConnectionState.Open)
{
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
value = dataReader["amount"].ToString();
}
dataReader.Close();
connection.Close();
}
These are the commands:
public string value;
public static string Konekcija = "Server=127.0.0.1; Database=CardIgrica; Uid=admin; Pwd=admin;";
public string komanda = "SELECT amount FROM CardIgrica.creaures WHERE id = '1';";
MySqlConnection connection = new MySqlConnection(Konekcija);
MySqlCommand cmd = new MySqlCommand(komanda, connection);
connection.Open();
try this for the select
public string value {get; set;}
string komanda ="SELECT amount FROM CardIgrica.creaures WHERE id = 1";
Try this
using (SqlConnection conn = new SqlConnection(Konekcija))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clear();
cmd.CommandText = komanda ;
conn.Open();
var dataReader= cmd.ExecuteReader();
while (result.Read())
{
value = dataReader["amount"].ToString();
}
conn.Close();
}
If you need single value, you can use cmd.ExecuteScalar(); instead of cmd.ExecuteReader();
because ExecuteScalar() will return single value.
First open your sql connection then make object of MySqlCommand like below:
MySqlConnection connection = new MySqlConnection(Konekcija);
connection.Open();
MySqlCommand cmd = new MySqlCommand(komanda, connection);