a few query with one sql connection - c#

private void button5_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='1'", conn);
conn.Open();
label1.Text = cmd.ExecuteReader().ToString();
conn.Close();
SqlConnection conn1 = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='2'", conn1);
conn1.Open();
label2.Text = cmd1.ExecuteReader().ToString();
conn1.Close();
SqlConnection conn2 = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd2 = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='3'", conn2);
conn2.Open();
label3.Text = cmd2.ExecuteReader().ToString();
conn2.Close();
}
I fetch the label texts from database. But in every fetching operation I open a connection in order to write a query. This is my first project in C#. How can I write a few query without opening many connections ? can anyone help me?

use using-statement to ensure that a connecion gets closed even in case of exception. You should always use it when a class implements IDisposable.
With Connection-Pooling you're not always opening and closing connections when you call con.Open() or con.Close(). Actually Close just makes the connection reusable, otherwise it would be marked as "in use". So it's good practise to close connections as soon as possible.
You could use a DataAdapter to fill a DataTable with one query. Then you would have all three records and could take what you need:
using (var conn = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True"))
{
var sql = "select label_sh from label_text where label_form_labelID IN('1','2','3') and label_form='2'";
using (var da = new SqlDataAdapter(sql, conn))
{
da.Fill(table); // you don't need to open a connection when using a DataAdapter
}
}
label1.Text = table.AsEnumerable()
.Single(r => r.Field<int>("label_form_labelID") == 1)
.Field<String>("label_sh");
label2.Text = table.AsEnumerable()
.Single(r => r.Field<int>("label_form_labelID") == 2)
.Field<String>("label_sh");
label3.Text = table.AsEnumerable()
.Single(r => r.Field<int>("label_form_labelID") == 3)
.Field<String>("label_sh");
Note that you need to add using System.Linq; for Linq-To-DataTable.

There's no need to close the connection each time. You can even reuse the SqlCommand variable in your example.
private void button5_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='1'", conn);
conn.Open();
label1.Text = cmd.ExecuteReader().ToString();
cmd.CommandText ="select label_sh from label_text where label_form='2' and label_form_labelID='2'";
label2.Text = cmd.ExecuteReader().ToString();
cmd.CommandText = "select label_sh from label_text where label_form='2' and label_form_labelID='3'"
label3.Text = cmd.ExecuteReader().ToString();
conn.Close();
}

You can reuse your SqlConnection for all the SqlCommand objects and after your are finished you can close the SqlConnection:
SqlConnection conn = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='1'", conn);
label1.Text = cmd.ExecuteReader().ToString();
SqlCommand cmd1 = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='2'", conn);
label2.Text = cmd1.ExecuteReader().ToString();
SqlCommand cmd2 = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='3'", conn);
label3.Text = cmd2.ExecuteReader().ToString();
conn.Close();
But it's even better for the performance to create one SQL query to retrieve your labels.

Well, I suggest you to create only one connection to de DB
SqlConnection conn = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
and then you can use SQL IN Operator to make only one query like this
select label_sh
from label_text
where label_form='2' and label_form_labelID IN ('1','2','3')
SQL IN Operator

Just showing another method which only require a single connection, a single command and a single data reader.
While Tim Schmelter approach is the most effective in your case, this a demo of the NextResult method of a DataReader.
Notice how the sql query in the SqlCommand included 3 sub queries separated by a semicolon. Whenever you call NextResult, you move to the next query.
using (var connection = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True"))
using (var command = new SqlCommand(
#"select label_sh from label_text where label_form='2' and label_form_labelID='1';
select label_sh from label_text where label_form='2' and label_form_labelID='2';
select label_sh from label_text where label_form='2' and label_form_labelID='3'", connection))
using (var reader = command.ExecuteReader())
{
var label1 = reader["label_sh"];
reader.NextResult();
var label2 = reader["label_sh"];
reader.NextResult();
var label3 = reader["label_sh"];
}

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

Can't Establish A Connection To SQL Server Using ADO.NET

I'm trying to establish a connection to a local SQL server using this code:
dataGridView1.Visible = true;
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=.;Initial Catalog=Form;Integrated Security=True";
SqlCommand com = new SqlCommand("select * from Form", con);
SqlDataAdapter sda = new SqlDataAdapter(com);
dataGridView1.DataSource = sda;
But when I press the button in my form it doesn't show me the data! What am i doing wrong?
you need something like this
dataGridView1.Visible = true;
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=.;Initial Catalog=Form;Integrated Security=True";
con.Open()
SqlCommand com = new SqlCommand("select * from Form", con);
SqlDataAdapter sda = new SqlDataAdapter(com);
DataTable dt=new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;//set it to datatable
dataGridView1.DataBind();
You need to open the connection with con.Open();.
con.ConnectionString = #"Data Source=.;Initial Catalog=Form;Integrated Security=True";
SqlCommand com = new SqlCommand("select * from Form", con);
con.Open();
Also you had a lot of other problems like you don't dispose your resource which can lead to memory leak and not closing your connection, also you are not filling your adapter. Here is optimal way to doing it.
using(SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=Form;Integrated Security=True";))
{
con.Open();
SqlCommand com = new SqlCommand("select * from Form", con);
using(SqlDataAdapter sda = new SqlDataAdapter(com));
{
DataTable resultTbl = new DataTable();
sda.Fill(resultTbl);
dataGridView1.DataSource = resultTbl;
dataGridView1.DataBind();
}
}

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.

Incorrect syntax near the keyword 'where'

public bool location()
{
string OUI = "OUI";
SqlConnection con = new SqlConnection(#"Data Source=WIN-218NC1F1FE2\SQLEXPRESS;Initial Catalog=projet;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select max(id_reservation) from reservation");
cmd.Connection = con;
Int32 maxId = (Int32)cmd.ExecuteScalar();
string v = Convert.ToString(maxId);
//correct
SqlCommand q = new SqlCommand("insert into reservation(location) values('" + OUI + "') where id_reservation ='"+ maxId + "'", con);
SqlDataReader da = q.ExecuteReader();
return true ;
}
the probleme was in command where : Incorrect syntax near the keyword 'where'.
help !!!
You can not have a where clause in an insert statement. That's all that is to it. If you want to insert, remove the where clause. If you need to update records that match a condition, don't use insert but update.
Also, if you're not really interested in the result of a query, don't use ExecuteReader but ExecuteNonQuery.
Thorsten answer is clear an complete I am just adding the code for each case:
SqlConnection con = new SqlConnection(#"Data Source=WIN-218NC1F1FE2\SQLEXPRESS;Initial Catalog=projet;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select max(id_reservation) from reservation");
cmd.Connection = con;
Int32 maxId = (Int32)cmd.ExecuteScalar();
string ID=maxId.TOString();
//correct
/////INSERT
SqlCommand q = new SqlCommand("insert into reservation(location) values(#location,#ID)", con);
q.Parameters.AddWithValue( "#location",OUI);
q.Parameters.AddWithValue("#ID",ID);
q.ExecuteNonQuery();
return true ;
////////UPDATE
SqlCommand q = new SqlCommand("update reservation set location=#location where id_reservation =#ID", con);
q.Parameters.AddWithValue( "#location",OUI);
q.Parameters.AddWithValue("#ID",ID);
q.ExecuteNonQuery();
return true ;

fetching the label text from database in C#

private void button5_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='1'", conn);
conn.Open();
label1.Text = cmd.ExecuteReader().ToString();
conn.Close();
SqlConnection conn1 = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='2'", conn1);
conn1.Open();
label2.Text = cmd1.ExecuteReader().ToString();
conn1.Close();
SqlConnection conn2 = new SqlConnection("Data Source=MAZI-PC\\PROJECTACC;Initial Catalog=programDB;Integrated Security=True");
SqlCommand cmd2 = new SqlCommand("select label_sh from label_text where label_form='2' and label_form_labelID='3'", conn2);
conn2.Open();
label3.Text = cmd2.ExecuteReader().ToString();
conn2.Close();
}
I am developing a small project in C#... Using Visiual Studio 2010... I want to fetch the label texts from database in order to change the user interface language with a button...
I wrote this code but there is a problem in SQLDATAREADER
in label text parts it shows
System.Data.SqlClient.SqlDataReader
I cant fix, could you help me?
you can use ExecuteScalar()
label3.Text = (string) cmd2.ExecuteScalar();
if you want to use ExecuteReader you have to store the reader first, then call Read on it and fetch it values with reader.GetString(0);

Categories

Resources