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

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

Related

Handling Database Connection in C#

I am Creating WinForm application using C# and SqlServer. I have to handle many database CRUD Queries on it. And also there are so many forms and so many controllers.
Now I want to know is, If i create common class for handle database connectivity with many methods for open connection, close connection, execute Sql command or do any other data retrievals. This method is good or bad?
or below method for run every query is good or bad?
using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Initial Catalog=MYDB"))
{
connection.Open();
// Pool A is created.
}
which method is better for performance and security?
Here are some points to think about when using a connection.
1) Dispose the connection object as soon as you no longer need it by using the using statement:
using (var conn = new SqlConnection(connectionstring))
{
// your sql magic goes here
}
2) If you're not disposing the object immediately, you can make sure the connection is closed using a try-finally statement:
var conn = new SqlConnection(connectionstring);
try
{
// do sql shizzle
}
finally
{
conn.Close();
}
3) To prevent SQL injection, use parameterized queries, never concatenated strings
using (var conn = new SqlConnection(connectionstring))
{
conn.Open();
using(var comm = new SqlCommand("select * from FooBar where foo = #foo", conn))
{
comm.Parameters.Add(new SqlParameter("#foo", "bar"));
// also possible:
// comm.Parameters.AddWithValue("#foo", "bar");
using(var reader = comm.ExecuteReader())
{
// Do stuff with the reader;
}
}
}
4) If you're performing multiple update, insert or delete statements, and they all need to be succesful at once, use a transaction:
using (var conn = new SqlConnection(connectionstring))
{
conn.Open();
using(var trans = conn.BeginTransaction())
{
try
{
using(var comm = new SqlCommand("delete from FooBar where fooId = #foo", conn, trans))
{
comm.Parameters.Add(new SqlParameter { ParameterName = "#foo", DbType = System.Data.DbType.Int32 });
for(int i = 0; i < 10 ; i++)
{
comm.Parameters["#foo"].Value = i;
comm.ExecuteNonQuery();
}
}
trans.Commit();
}
catch (Exception exe)
{
trans.Rollback();
// do some logging
}
}
}
5) Stored procedures are used similarly:
using (var conn = new SqlConnection(connectionstring))
{
conn.Open();
using (var comm = new SqlCommand("FooBarProcedure", conn) { CommandType = CommandType.StoredProcedure })
{
comm.Parameters.Add(new SqlParameter("#FooBar", "shizzle"));
comm.ExecuteNonQuery();
}
}
(Source stored procedures: this Answer)
Multi threading: The safest way to use multi threading and SQL connections is to always close and dispose your connection object. It's the behavior the SqlConnection was designed for. (Source: Answer John Skeet)
Best practice is make a common DBHelper class and create CRUD methods into that class.
I am adding code snippet.This may help you.
web.config
<connectionStrings>
<add name="mssqltips"
connectionString="data source=localhost;initial catalog=mssqltips;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
DBHelper.cs
//Opening Connection
public SqlConnection GetConnection(string connectionName)
{
string cnstr = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
SqlConnection cn = new SqlConnection(cnstr);
cn.Open();
return cn;
}
//for select
public DataSet ExecuteQuery(
string connectionName,
string storedProcName,
Dictionary<string, sqlparameter=""> procParameters
)
{
DataSet ds = new DataSet();
using(SqlConnection cn = GetConnection(connectionName))
{
using(SqlCommand cmd = cn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcName;
// assign parameters passed in to the command
foreach (var procParameter in procParameters)
{
cmd.Parameters.Add(procParameter.Value);
}
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
return ds;
}
//for insert,update,delete
public int ExecuteCommand(
string connectionName,
string storedProcName,
Dictionary<string, SqlParameter> procParameters
)
{
int rc;
using (SqlConnection cn = GetConnection(connectionName))
{
// create a SQL command to execute the stored procedure
using (SqlCommand cmd = cn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcName;
// assign parameters passed in to the command
foreach (var procParameter in procParameters)
{
cmd.Parameters.Add(procParameter.Value);
}
rc = cmd.ExecuteNonQuery();
}
}
return rc;
}
If you do not want to dispose context every time you can create repository class and inject SqlConnection inside.
using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Initial Catalog=MYDB"))
{
repository.SetConnection(connection);
var values = repository.GetSomething();
}
And Create Class:
public Class Repository
{
private SqlConnection _connection {get; set;}
public void SetConnection(SetConnection connection)
{
_connection = connection;
}
public string GetSomething()
{
_connection.Open();
//do stuff with _connection
_connection.Close();
}
}
Anyway I recommend you to read about ORM's (Entity Framework or Dapper) and SQL injection attack.

MySql connection in differenct class C#

Okey, so I am new to C# and I have tried to move my Mysql connection string to another class but I can't seem to open the connection once I call the method and I really can't see what's wrong.
So this is the connection method in a new class(DatabaseC)
public static void Connection()
{
try
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["cs"];
string conn = conSettings.ConnectionString;
MySqlConnection connect = new MySqlConnection(conn);
connect.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
And here I call the method in a Form
private bool validate_login(string u, string p)
{
DatabaseC.Connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT * FROM account WHERE Password COLLATE latin1_general_cs = #password AND User COLLATE latin1_general_cs = #username";
cmd.Parameters.AddWithValue("#username", u);
cmd.Parameters.AddWithValue("#password", p);
MySqlDataReader login = cmd.ExecuteReader();
}
Sorry for if the code looks bad but as I said im new.
You should return the instance of the MySqlConnection opened
public static MySqlConnection Connection()
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["cs"];
string conn = conSettings.ConnectionString;
MySqlConnection connect = new MySqlConnection(conn);
connect.Open();
return connect;
}
Now you can change your calling code to receive the connection and use it
private bool validate_login(string u, string p)
{
using(MySqlConnection cnn = DatabaseC.Connection())
using(MySqlCommand cmd = cnn.CreateCommand())
{
cmd.CommandText = "......"
...
using(MySqlDataReader reader = cmd.ExecuteReader())
{
.....
} // Here the reader is closed and destroyed
} // Here the connection closed and destroyed with the command
}
Notice that a connection is a disposable object and thus you should be sure to destroy it once you have finished to use it. This is the work of the using statement.
Another problem fixed with this code is the fact that a command needs to know the connection to use, your actual code doesn't link the command with the connection and thus it cannot work.
EDIT: you comment below should be added to the answer. The Try/Catch in the Connection method should be removed. You do nothing there and catching the exception creates only complications in the calling code that need to handle a null return value. It is better to let the exception bubble up until there is a method that has something to do with that (like logging it for example)
Actually you need to open the connection where you are using the connection, try this way
public static MySqlConnection Connection()
{
try
{
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["cs"];
string conn = conSettings.ConnectionString;
MySqlConnection connect = new MySqlConnection(conn);
return connect;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
then
private bool validate_login(string u, string p)
{
DatabaseC.Connection().Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "SELECT * FROM account WHERE Password COLLATE latin1_general_cs = #password AND User COLLATE latin1_general_cs = #username";
cmd.Parameters.AddWithValue("#username", u);
cmd.Parameters.AddWithValue("#password", p);
MySqlDataReader login = cmd.ExecuteReader();

Load two / several MS Access Table into C# Windows Form

I´m asking how to connect two or more tables from an MS Access table into c# Windows forms?.
I get the error, that ue cant find the second table:
public partial class Form1 : Form
{
private OleDbConnection connection = new OleDbConnection();
private OleDbConnection connection2 = new OleDbConnection();
public Form1()
{
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\MitarbeiterDaten2.accdb;
Persist Security Info=False;";
connection2.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\DatenbankAbteilung.accdb;
Persist Security Info=False;";
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader["ABTEILUNG"].ToString());
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
}
Anybody got an solution?
Its just about, how to connect two or more MS Access tables into C# Windows forms.
You can reuse the the objects, and can get data from various tables or databases, as :
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader("ABTEILUNG").ToString());
}
reader.Close(); //' Always Close ther Reader. Don't left it open
connection2.Open();
command.Connection = connection2; //' Reusing Same Command Over New Connection
command.CommandText = "Select Field2 from Table2";
while (reader.Read)
{
if (!(Convert.IsDBNull(reader("Field2")))) //' Checking If Null Value is there
{
Abteilung.Items.Add(reader("Field2").ToString());
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
connection2.Close();
}
}
How about using using blocks to take care of the commands and connections and then using DataAdapter to get the job done easily. I use some code like this.
DataSet ds = new DataSet();
using (OleDbConnection con = new OleDbConnection(MDBConnection.ConnectionString))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT Column FROM Table1", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
using (OleDbCommand cmd = new OleDbCommand("SELECT AnotherColumn FROM Table2", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
return ds;

Can't get output from SQL Server Compact

I have the following code behind a button in Visual Studio 2010
private void button1_Click(object sender, EventArgs e)
{
SqlCeConnection Con = new SqlCeConnection();
Con.ConnectionString = "Data Source = 'DB.sdf';" + "Password='my Password';";
SqlCeCommand Query = new SqlCeCommand("SELECT Password FROM Admin");
try
{
Con.Open();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlCeDataReader Reader=Query.ExecuteReader();
MessageBox.Show(Reader["Password"].ToString());
}
It works fine execute and no exception in connection but when I press the button it raises an exception saying
Error: Execute Reader Connection Property Has Not Been Initialized
I'm not going to attempt to comment on database access code in a UI event handler, it will detract from the answer too much. All I will say is, try not to do it.
You haven't associated the connection with the command, either in the command constructor or the relevant Connection property.
I would re-write the entire method to the following to cut out the dangerous try-catch (catching everything, very bad practice) and to utilise the fact using statements also handle object disposal for you:
string password = null;
using (var conn = new SqlCeConnection("Data Source = 'AlviMBRental.sdf'; Password='my Password';"))
using (var comm = new SqlCeCommand("SELECT Password FROM Admin", conn))
{
conn.Open();
using (var reader = comm.ExecuteReader())
{
password = (string)reader["Password"];
} // Dispose reader
// Alternatively, if the resultset is single column and single row, you can do:
var passwordScalar = (string)comm.ExecuteScalar();
} // Dispose command, close / dispose connection.
MessageBox.Show(password ?? "No password found.");
You are not associating your command with your connection - try this:
SqlCeConnection Con = new SqlCeConnection("Data Source = 'AlviMBRental.sdf';Password='my Password';";
SqlCeCommand Query = new SqlCeCommand("SELECT Password FROM Admin", Con); // <== specify "Con" here!
Otherwise, your SqlCeCommand has no connection to work with....
Try like this:
private void button1_Click(object sender, EventArgs e)
{
var connectionString = "Data Source='AlviMBRental.sdf';Password='my Password';";
using (var con = new SqlCeConnection(connectionString))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT Password FROM Admin";
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
MessageBox.Show(reader["Password"].ToString())
}
}
}
}
Make sure you have associated the connection with the command object. Also make sure you have wrapped IDisposable objects in using statements as shown in my example.

Connection string property has not be initialized

When I add a Car in my application I get
The ConnectionString property has not been initialized.
I have the problem of ConnectionString property. I check similar question of mine but I found nothing helpfulness.
I use a class connection named dbConnection.cs:
class dbConnection
{
//Connection to database
private string con = "Data Source=(local)\\SQLEXPRESS; Initial Catalog=MLQ7024; Integrated Security=TRUE".ToString();
public string Con
{
get
{
return con;
}
}
}
This is the code of my button
private void btnAddCar_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(dc.Con))
{
DataTable dtCar = new DataTable();
BindingSource Car_bs = new BindingSource();
using (SqlCommand cmd = new SqlCommand("sp_Add_Car", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
//......
con.Open();
cmd.ExecuteNonQuery();
con.Close();
dtCar.Clear();
da.Fill(dtCar);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\t" + ex.Source);
}
}
}
refreshCar();
}
This is the code of an another button working well without error
private void btnAddPayment_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(dc.Con))
{
DataTable dtPayment = new DataTable();
using (SqlCommand cmd = new SqlCommand("sp_Add_Paiements", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#id_paiement", SqlDbType.Char).Value = txtBoxPaymentId.Text;
cmd.Parameters.Add("#montant", SqlDbType.SmallMoney).Value = txtBoxAmount.Text;
cmd.Parameters.Add("#id_Location", SqlDbType.Char).Value = cmbpaymentLesaseId.Text;
//cmd.Parameters.Add("#status", SqlDbType.Char).Value = txtBoxStatusPayment.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
dtPayment.Clear();
da.Fill(dtPayment);
btnAddLease.Hide();
refreshPayments();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\t" + ex.Source);
}
}
}
btnAddPayment.Hide();
}
You aren't showing where you have initialized your dbConnection class. Changing it all to static will probably help, I'm guessing:
static class dbConnection
{
//Connection to database
private static string con = "Data Source=(local)\\SQLEXPRESS; Initial Catalog=MLQ7024; Integrated Security=TRUE"
public static string Con
{
get
{
return con;
}
}
}
If your dbConnection class worked in one method but not the other, chances are you had it initialized in one and not the other. Unless you have to deal with different database connections, using a static class for your database connections is probably the best route.
Then you change your calling method like this:
using (SqlConnection con = new SqlConnection(dbConnection.Con))
{
// blah-blah
}
Assuming dc is your connection, then it has to be initialized with a connection string. Maybe - if it's a class - you have to set some properties, like database path, etc.
SqlConnection Con= New SQLConnection(#"Data Source=(local)\\SQLEXPRESS; Initial Catalog=MLQ7024; Integrated Security=TRUE");

Categories

Resources