Error while converting string to SqlConnection - c#

I'm getting this error:
Cannot implicitly convert type string to System.Data.SqlClient.SqlConnection
Here is my C# code.
protected void Button1_Click(object sender, EventArgs e)
{
//login button
SqlConnection sqlConn = "Your Conncetion String"; //The error is here
sqlConn.Open();
SqlCommand sqlComm = new SqlCommand();
sqlComm.CommandText = String.Format("select * from users where userName=#userName and password=#password");
sqlComm.Parameters.AddWithValue("#userName", TextBox1.Text.Trim());
sqlComm.Parameters.AddWithValue("#password", TextBox2.Text.Trim());
sqlComm.CommandType = CommandType.Text;
sqlComm.Connection = sqlConn;
SqlDataReader sqlRead = sqlComm.ExecuteReader();
if (sqlRead.Read())
{
Session["username"] = sqlRead["username"];
}
// SqlRead.Close();
//sqlConn1.Close();
Response.Redirect("Default.aspx");
}
Can someone explain what this error means and how to fix it?

I understand you have a connection string and want a SqlConnection object. You can use one of its constructors:
string connString = "Your Conncetion String"; // valid connection string
var sqlConn = new SqlConnection(connString);
It will be best if you use using keyword as this will take care of closing the connection properly. You should also use using for your SqlReader.
using (var sqlConn = new SqlConnection(connString))
{
sqlConn.Open();
// the rest of the code
}

Change
SqlConnection sqlConn = "Your Conncetion String";
To
SqlConnection sqlConn = new SqlConnection("Your Conncetion String");

it should be
SqlConnection sqlConn = new SqlConnection("Your Conncetion String");
You can read it from web.config
SqlConnection sqlConn = new
SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
now this error The name 'ConfigurationManager' does not exist in the current context
You have to add a reference to the System.Configuration.dll
then add using System.Configuration; to your class.
You can now access your config file like this:
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

Related

how to build a SQL connection using C# in Visual Studio 2017?

I've always used Oledb Connection.
but now I need to connect with my Database via Sql connection
yet I don't know how to do so,
can some one provide me an example of a database connected with sql connection?
this code needs a sql connection to be done successfully.
protected void Button1_Click(object sender, EventArgs e)
{
string st = this.TextBox1.Text;
string sqlstr2 = "select * from hsinfo WHERE rname='"+st+ "'";
SqlCommand cmd = new SqlCommand(sqlstr2,);
using (SqlDataReader rd = cmd.ExecuteReader())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
You can check the official Microsoft page for more details SqlConnection Class, but I will reproduce the given example below ...
Aditionally you can check also the Connection String Syntax linked in the previous link.
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();
}
}
This is a simple example code and it's working. This might help you.
Here NextMonth,NextYear,ProcessedDate are auto calculated values comes from another function don't think about that.
String cs = #"Data Source=LENOVO-G510;Initial Catalog=Nelna2;Persist Security Info=True;User ID=sa;Password=123";
protected void Save_Click(object sender, EventArgs e)
{
// SqlConnection con = new SqlConnection(cs);
using (SqlConnection con = new SqlConnection(cs))
{
try
{
SqlCommand command5 = new SqlCommand("insert into MonthEnd (month,year,ProcessedDate) values (#month2,#year2,#ProcessedDate2) ", con);
command5.Parameters.AddWithValue("#month2", NextMonth);
command5.Parameters.AddWithValue("#year2", NextYear);
command5.Parameters.AddWithValue("#ProcessedDate2", ProcessedDate);
command5.ExecuteNonQuery();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
}
}
Connection string can be found in DB properties. right click on DB -> properties and Get the Connection String
There is no enougth information to build connection for you, but in the shortes you sth like this:
Server=...;Database=...;User ID=...;Password=...;
For more information just check ConnectionStrings website.
try below code and for more information about c# SQL server connection see this SQL Server Connection
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I would do something like this:
public static List<Test> GetTests(string testVariable)
{
DataTable result = new DataTable();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
{
connection.Open();
GetQuery(
connection,
QueryGetTests,
ref result,
new List<SqlParameter>()
{
new SqlParameter("#testVariable", testVariable)
}
);
return result.Rows.OfType<DataRow>().Select(DataRowToTest).ToList();
}
}
private static void GetQuery(SqlConnection connection, string query, ref DataTable dataTable, List<SqlParameter> parameters = null)
{
dataTable = new DataTable();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandTimeout = 120;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
using (SqlDataAdapter reader = new SqlDataAdapter(command))
{
reader.Fill(dataTable);
}
}
}
I think this can help you.
string sqlString = "select * from hsinfo WHERE rname=#st";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.Add("#st", st);
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (rd.Read())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
}
}
Trick:
Create a file with .udl Extension on your Desktop
Run it by Double click
Compile form by Choosing provider, username, password, etc...
Test connection and save
Close the form
Open now the .udl file with Notepad
You will see the connection string that you can use with ADO.NET

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();

ExecuteNonQuery: Connection property not initialized

How do i resolve ExecuteNonQuery: Connection property is not initialized. I already made my cmd.Connection = con; this is my code please help
Private void button1_Click(object sender, EventArgs e)
{
if (img_file != null)
{
FileStream fs = new FileStream(img_file, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[]image = new byte[fs.Length];
fs.Read(image,0,Convert.ToString(fs.Length));
fs.Close();
SqlCommand cmd = new SqlCommand("INSERT INTO member_details (name,address,email,phone_number,picture) VALUES('"+textBox1.Text+"', '"+textBox2.Text+"', '"+textBox3.Text+"', #pic)", con);
SqlParameter prm = new SqlParameter("#pic", SqlDbType.VarBinary, image.Length, ParameterDirection.Input, false, 0,0, null, DataRowVersion.Current, image);
cmd.Parameters.Add(prm);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
}
You can use below code as reference to fix your code:
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statemnt Here";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
You can simply initialize and close connections by
using(SqlConnection con = new SqlConnection(connectionstring))
{
--write all your command n execution code here---;
}
Apart from this, one suggestion, you need to use parameterized query or Stored Proc with paramerts to avoid SQLInjection:
Reference to SQLInjection : https://www.veracode.com/security/sql-injection

Connection string not working in C# windows application

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())
{
...
...
}

SQL query is not being executed in C#

I have a SQL query and I want to execute it in C# on a button click, but when I click the
button the database is not being affected:
private void button1_Click(object sender, EventArgs e) {
String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.CommandText = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";
con.Close();
}
The code you want is this:
String ConnectionString = "Data Source=localhost;Initial Catalog=mydb;Integrated Security=True";
String sql = "INSERT INTO MedTab (MedID,MedName,Manf,MedProd,MedExp,TimeLeft,InStock) VALUES (4,'sdfs','sdfsd','sdfsdf','sdfsdf','sdfsd',33);";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
cmd.ExecuteNonQuery();
}
Add cmd.ExecuteNonQuery after setting the command text.
You need to actually execute the query (try ExecuteNonQuery).
You're currently opening a connection, setting the statement to execute, then just closing the connection.

Categories

Resources