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);
Related
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();
I want to know how I could browse picture on desktop and upload the pic to my form and then save it to my database. This is what my friend did but it doesn't work for me. I don't know why please help.
MemoryStream ms = new MemoryStream();
pictureBox11.Image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
SqlConnection con = new SqlConnection("Data Source=LAPTOP;Initial Catalog=db;Integrated Security=True");
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"INSERT INTO tblperson([product name],[pics],[user]) VALUES(#value1,#value2,#value3)";
cmd.Parameters.AddWithValue("#value1", txtproductname.Text);
cmd.Parameters.AddWithValue("#value2", picbase64);
cmd.Parameters.AddWithValue("#value3", lbluser.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Picture Saved");
con.Close();
txtproductname.Text = "";
pictureBox11.Image = LessonMidterm1.Properties.Resources.Person;
I am making emp time attendance register. I am using below code .. here insert query working fine and time-in successfully save in database timein field. Update query also execute successfully but databasae not updated...anyone please help for this...
private void checkin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source............");
conn.Open();
SqlCommand comm = new SqlCommand();
comm.CommandText = "insert into timeatten (id,name,timein)values('" +comboBox1.Text+"','"+textBox1.Text+"','"+textBox2.Text+"' )";
comm.Connection = conn;
comm.ExecuteNonQuery();
MessageBox.Show("Successfully check in");
conn.close();
}
private void checkout_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source.............");
conn.Open();
SqlCommand comm = new SqlCommand();
comm.CommandText = "update timeatten set timeout='" + textBox2.Text + "' where id='" + comboBox1.Text +"'";
MessageBox.Show("Successfully Checkout");
conn.close();
}
I think you're missing these two lines in checkout_Click:
comm.Connection = conn;
comm.ExecuteNonQuery();
SqlConnection con = new SqlConnection( "Data Source=AMBADNYA-PC;Initial
Catalog=MYRAWPRO;Persist Security Info=True;User ID=sa;Password=sa");
string query = "DELETE FROM Sales WHERE Sales_ID =" +
dataGridViewProduct.SelectedRows[0].Cells[0].Value.ToString();
SqlCommand com = new SqlCommand();
com.CommandText = query;
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
con.Close();
MessageBox.Show("Deleted");
but it show error
Invalid column name 'uiui'.
uiui is the column value. What am I doing wrong?
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"];
}