I have written the following code to query stuff from a SQL Server database. The query in the first reader works, but not in the second. I just can't seem to figure out why as the approach is exactly the same in both readers. Any help is much appreciated.
The parameters for the commands are given in the function above which isn't in the code btw.
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "...";
conn.Open();
SqlCommand command = new SqlCommand("SELECT stuff FROM table WHERE Belegnummer= #n and Belegjahr=#j", conn);
command.Parameters.Add(new SqlParameter("n", nr));
command.Parameters.Add(new SqlParameter("j", jahr));
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
r = reader.GetInt32(0);
}
}
command.Dispose();
SqlCommand command2 = new SqlCommand("SELECT stuff1, stuff2, stuff3 FROM sameTable WHERE BelID = #rnr", conn);
command2.Parameters.Add(new SqlParameter("rnr", r));
using (SqlDataReader reader2 = command2.ExecuteReader())
{
while (reader2.Read())
{
// variables are defined somewhere above
b = reader2.GetInt32(0);
j = reader2.GetInt32(1);
m = reader2.GetInt32(2);
}
}
}
Please post the error messages as well.
You may run into trouble with DbNull values. Check for DbNull before you parse the values with:
SqlReader.IsDBNull(column)
Or load the Data into a DataTable:
DataTable dt = new DataTable();
using (SqlDataReader reader = cmd1.ExecuteReader())
{
dt.Load(reader);
}
Related
I can't extract the values through a query and insert them into textboxes
Where am I going wrong?
Request.QueryString.Get("ID_Persona");
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM Persona WHERE ID = #id";
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID","");
cmd.Parameters.AddWithValue("#Nome", TextBox1.Text);
cmd.Parameters.AddWithValue("#Cognome", TextBox15.Text);
cmd.Parameters.AddWithValue("#Email", TextBox20.Text);
cmd.Parameters.AddWithValue("#CodiceFiscale", TextBox22.Text);
con.Open();
cmd.ExecuteNonQuery();
}
You need to use ExecuteReader to read values, something like this:
var connectionString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM Persona WHERE ID = #id";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#ID", Request.QueryString.Get("ID_Persona"));
con.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
//IDTextBox? = rdr["Id"].ToString(),
TextBox1.Text = rdr["Nome"].ToString(),
TextBox15.Text = rdr["Cognome"].ToString(),
TextBox20.Text= rdr["Email"].ToString(),
TextBox22.Text= rdr["CodiceFiscale"].ToString(),
}
}
}
}
You should use a ExecuteReader() instead of ExecuteNonQuery() since ExecuteNonQuery is meant for DML operations. Again, you need only the ID value to be passed then why you are passing unnecessary parameters to your query. Remove them all. An example below
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader["Email"]));
}
I can see several issues:
You should use ExecuteReader() instead of ExecuteNonQuery()
You should provide just 1 parameter - #ID; I doubt if it should have an empty value.
You should wrap IDisposable into using
Code:
string query =
#"SELECT ID,
Nome,
Cognome,
Email,
CodiceFiscale
FROM Persona
WHERE ID = #id";
using (SqlConnection con = new SqlConnection(...))
{
con.Open();
using SqlCommand cmd = new SqlCommand(query, con)
{
// I doubt if you want empty Id here.
// I've assumed you want to pass ID_Persona
cmd.Parameters.AddWithValue("#ID", Request.QueryString.Get("ID_Persona"));
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
TextBox1.Text = Convert.ToString(reader["Nome"]);
TextBox15.Text = Convert.ToString(reader["Cognome"]);
TextBox20.Text = Convert.ToString(reader["Email"]);
TextBox22.Text = Convert.ToString(reader["CodiceFiscale"]);
}
}
}
}
Am trying to populate a listbox with values generated by a query, the code runs without any problems but the listbox is not displaying any results, what am i doing wrong, is there anything missing??
String sql = "SELECT * FROM products where code = "+textBox1.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, conn); //c.con is the connection string
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
listBox1.Items.Add(reader["description"].ToString() + ": "+reader["price"].ToString());
listBox1.Refresh();
}
reader.Close();
conn.Close();
}
}
If your code column is of string type then
String sql = "SELECT * FROM products where code = '"+textBox1.Text + "'";
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, conn); //c.con is the connection string
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
listBox1.Items.Add(reader["description"].ToString() + ": "+reader["price"].ToString());
}
reader.Close();
}
conn.Close();
}
Also to add all values, use while instead of if to traverse all the records in the reader. And also close the connection after the using statement.
I am sure the wrong sequence is causing the issue.
I'm making some assumptions here about your code, is 'code' a number? If not, did you try:
String sql = "SELECT * FROM products where code = '"+textBox1.Text+"'";
?
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection("Data Source=NSIC;Initial Catalog=Dev;User ID=sa;Password=123456"))
{
// SqlDataAdapter adapter = new SqlDataAdapter("Select * from Employee", connection);
connection.Open();
//adapter.Fill(ds);
using (SqlCommand command = new SqlCommand("Select * from Employee", connection))
{
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read()) //Error is here
{
var table = new DataTable();
table.Load(reader);
ds.Tables.Add(table);
}
}
}
}
GridView1.DataSource = ds;
I am trying to retrieve data from data sql server.but error on while(Reader.read()).
Invalid attempt to call Read when reader is closed on
while(Reader.read()).
why?
The problem here is that you're using DataTable.Load inside the while-loop.
The while-loop basically says "While there are more rows", and then you call DataTable.Load that loads all the rows, and then go back to check for more.
Instead you can simply remove the while loop altogether:
using (SqlDataReader reader = command.ExecuteReader())
{
var table = new DataTable();
table.Load(reader);
ds.Tables.Add(table);
}
I think using CommandBehavior.CloseConnection is messing with your reader.
Try using it like below;
using (SqlConnection connection = new SqlConnection("Data Source=NSIC;Initial Catalog=Dev;User ID=sa;Password=123456"))
using (SqlCommand command = new SqlCommand("Select * from Employee", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var table = new DataTable();
table.Load(reader);
ds.Tables.Add(table);
}
}
}
I keep getting this error
There is already an open datareader associated with this command which must be closed first.
at this line of code:
using (SqlDataReader rd = command.ExecuteReader())
I have tried to close all other SqlDataReader's in class but it didn't work.
public int SifreGetir(string pEmail) {
SqlCommand command = con.CreateCommand();
command.CommandText = #"SELECT Sifre FROM Kullanici WITH (NOLOCK) WHERE email=#email";
command.Parameters.Add("#email", SqlDbType.VarChar);
command.Parameters["#email"].Value = pEmail;
using (SqlDataReader rd = command.ExecuteReader())
{
rd.Read();
string pass = rd["Sifre"].ToString();
int p = Convert.ToInt32(pass);
return p;
}
}
Try implementing your code in the below format
using(SqlConnection connection = new SqlConnection("connection string"))
{
connection.Open();
using(SqlCommand cmd = new SqlCommand("your sql command", connection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
//do something
}
}
}
}
}
The using statement will ensure disposal of the objects at the end of the using block
try this:
public int SifreGetir(string pEmail) {
SqlConnection con = new SqlConnection("Your connection string here");
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
SqlCommand command = new SqlCommand(#"SELECT Sifre FROM Kullanici WITH (NOLOCK) WHERE email=#email",con);
command.CommandType = CommandType.Text;
command.Parameters.Add("#email", SqlDbType.VarChar).Value = pEmail;
da.Fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
string pass = dr["Sifre"].ToString();
int p = Convert.ToInt32(pass);
return p;
}
con.Close();
}
You have used Using Keyword for SQL Reader but There is nothing to take care of your command and connection object to dispose them properly. I would suggest to try disposing your Connection and command both objects by Using keyword.
string connString = "Data Source=localhost;Integrated " + "Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new;
cmd.CommandText = "SELECT ID, Name FROM Customers";
conn.Open();
using (SqlDataReader rd = command.ExecuteReader())
{
rd.Read();
string pass = rd["Sifre"].ToString();
int p = Convert.ToInt32(pass);
return p;
}
}
I am programmer in asp.net. I am using C#. I have written very lengthy code for query execution in each time. How to re-factor and organize the following code?
MySqlConnection connection = new MySqlConnection(connstring);
string query = "Select fo_region_Name from fo_region where fo_region_DeleteStatus=0";
MySqlCommand command = new MySqlCommand(query, connection);
MySqlDataReader reader;
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
ddl_Country.Items.Add(UppercaseFirst(reader[0].ToString()));
}
connection.Close();
query = "Select Fo_Nationality_Name from fo_Nationality a, Fo_region b where a.Fo_Nationality_Type=1 and "
+ "LEFT(a.Fo_Nationality_Code,2)=LEFT(b.fo_region_Name,2) and a.Fo_Nationality_DeleteStatus=0 and "
+ "b.fo_region_DeleteStatus=0 Union Select Fo_Nationality_Name from fo_nationality where Fo_Nationality_DeleteStatus=0";
command = new MySqlCommand(query, connection);
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
ddl_Nationality.Items.Add(UppercaseFirst(reader[0].ToString()));
}
connection.Close();
query = "select mcs_CreditCard_CardName from mcs_creditcard where mcs_CreditCard_DeleteStatus=0";
command = new MySqlCommand(query, connection);
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
ddl_CreditCard.Items.Add(UppercaseFirst(reader[0].ToString()));
}
connection.Close();
Some thoughts:
Use multiline strings to format your SQL statements.
There is no need to close and reopen the connection betwween each command execution.
There is also no need to create new connection and command objects (in this case)
If you have parameters on the command objects, it is easier to create new command objects, rather than clearing out the old parameters
Use var statements to have the C# compiler automatically determine the variable type for you.
Wrap objects that need to be disposed, in a using block.
using (var connection = new MySqlConnection(connstring)) {
connection.Open();
using (var command = new MySqlCommand()) {
MySqlDataReader reader;
command.CommandText = #"
SELECT fo_region_Name
FROM fo_region
WHERE fo_region_DeleteStatus=0
";
using (reader = command.ExecuteReader()) {
while (reader.Read()) {
ddl_Country.Items.Add(UppercaseFirst(reader[0].ToString()));
}
}
command.CommandText = #"
SELECT Fo_Nationality_Name
FROM fo_Nationality a,
Fo_region b
WHERE a.Fo_Nationality_Type = 1
AND LEFT(a.Fo_Nationality_Code,2) = LEFT(b.fo_region_Name,2)
AND b.fo_region_DeleteStatus=0
UNION SELECT Fo_Nationality_Name
FROM fo_nationality
WHERE Fo_Nationality_DeleteStatus=0
";
using (reader = command.ExecuteReader()) {
while (reader.Read()) {
ddl_Nationality.Items.Add(UppercaseFirst(reader[0].ToString()));
}
}
command.CommandText = #"
SELECT mcs_CreditCard_CardName
FROM mcs_creditcard
WHERE mcs_CreditCard_DeleteStatus = 0
";
using (reader = command.ExecuteReader()) {
while (reader.Read()) {
ddl_Nationality.Items.Add(UppercaseFirst(reader[0].ToString()));
}
}
}
}
With LINQ (add a using System.Data.Common statement):
using (reader = command.ExecuteReader()) {
/*while (reader.Read()) {
ddl_Country.Items.Add(UppercaseFirst(reader[0].ToString()));
}*/
ddl_Country.Items.AddRange((
from DbDataRecord row in reader
select new ListItem(
UppercaseFirst(reader.GetString(0))
)
).ToArray());
}
Maybe use can use EnterpriseLibrary, to reduce amount of code that deals with database.