Connection string not working in C# windows application - c#

For some reasons, I am unable to establish a data connection using my connection string. I was doing with the below code
var connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection(connectionString);
cmd.Connection = connectionString;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = " dbo.SelectAll";
SqlParameter param = new SqlParameter("#tradeDate","201401");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
cmd.Parameters.Add(param);
But for some reasons when I am initializing the connection property to my command using cmd.Connection = connectioString, is is throwing an exception as follows
Cannot implicitly convert type 'string' to
'System.Data.SqlClient.SqlConnection'

You're confusing the connection string needed to connect to the database and the actual SqlConnection.
try this (for your specific code):
cmd.Connection = con;
According to MSDN here is a proper example:
private static void CreateCommand(string queryString, string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Link to original article: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx

I think you need just
cmd.Connection = con;
You are try to do set your SqlCommand.Connection property with your connection string. But this property is for specify your SqlConnection object, not your connection string.
From documentation;
Gets or sets the SqlConnection used by this instance of the
SqlCommand.
And since there is no implicit conversation from SqlConnection to string, that's why you get compile time error.
As a side note, use using statement to dispose your SqlConnection and SqlCommand like;
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
...
...
}
or you can use SqlConnection.CreateCommand() method to create your SqlCommand associated your SqlConnection inside your using statement like;
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = con.CreateCommand())
{
...
...
}

Related

How do inject from Asp.net to a SQL database?

I have a hard time figuring out what is wrong about my code. The purpose is to take data from a registering form in ASP to my user data columns in my SQL database.
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin
values(#UserName,#Password)";
SqlConnection cnn = new SqlConnection(cmd);
SqlCommand cmd2 = new SqlCommand(cmd, cnn);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();
You're using the connection string in the connection variable but the variable you're passing to SqlCommand is cnn which doesn't have a valid connection string associated with it.
I've cleaned up your code and made use of using block to ensure the correct manner of disposing the object. Please see below:
string connectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (var con = new SqlConnection(connectionString))
{
string query = "insert into UserLogin values(#UserName, #Password)";
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd.Parameters.AddWithValue("#Password", PasswordBox.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
You have two SqlConnection variable and assigning wrong one in the SqlCommand. The working code will be:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
try
{
string cmd = "insert into UserLogin values(#UserName, #Password)";
SqlCommand cmd2 = new SqlCommand(cmd, connection);
cmd2.Parameters.AddWithValue("#UserName", UsernameBox.Text);
cmd2.Parameters.AddWithValue("#Password", PasswordBox.Text);
cnn.Open();
cmd2.ExecuteNonQuery();

Attempting to open SQL Connection from console application - conn.open dies

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)

no value given fr one or more required parameters

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.

Best practices with oracle connection in C #

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

How to Execute Update SQL Script in ASP.Net

I have this code to execute a stored procedure (Update SP) in ASP.Net, unfortunately record is not updating when I run the code.
This is my code:
using (SqlConnection sqlConnection = Connt.GetConnection(TblName))
{
sqlConnection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter(SqlScript, sqlConnection))
{
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.Parameters.AddRange(SqlParam);
}
}
Where SqlScript is the variable for the stored procedure name and SqlParam is the parameters.
Please help me figure out what is wrong with my code.
Hi you can try something like this
SqlConnection sqlConnection = new SqlConnection();
SqlCommand sqlCommand = new SqlCommand();
sqlConnection.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=True";
public void samplefunct(params object[] adparam)
{
sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "SPName";
sqlCommand.Parameters.Add("#param1", SqlDbType.VarChar).Value = adparam[0];
sqlCommand.Parameters.Add("#param2", SqlDbType.VarChar).Value = adparam[1];
sqlCommand.Parameters.Add("#Param3", SqlDbType.VarChar).Value = adparam[2];
sqlCommand.ExecuteNonQuery();
}
Try:
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
With a Param:
command.Parameters.Add(new SqlParameter("#ID", 123));

Categories

Resources