I have this code and it does not work. Does anyone know why?
It did not return any data, but if run the query in SQL Server it returns the data.
using (SqlConnection connection = new SqlConnection(_dbContext.GetConnectionString()))
{
using (SqlCommand command = new SqlCommand())
{
StringBuilder stringQuery = new StringBuilder();
stringQuery.Append(" SELECT cd_material, ds_material");
stringQuery.Append(" FROM tbl_materiais");
stringQuery.Append(" WHERE ds_material like #Name");
command.Parameters.AddWithValue("#Name", "%" + name + "%");
command.CommandText = stringQuery.ToString();
command.CommandType = System.Data.CommandType.Text;
command.Connection = connection;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
_product = new ProductSell();
((IProduct)_product).ID = reader.GetFieldValue<int>(0);
((IProduct)_product).Name = reader.GetFieldValue<string>(1);
listProduct.ToList<IProduct>().Add(_product);
}
}
}
}
What is listProduct and why do you call its ToList<>()?
listProduct.ToList<IProduct>() returns a new instance of List<IProduct> that is forgotten after this line executes. Calling .Add(_product) on this returned list does not affect listProduct.
My problem stay here
while (reader.Read())
{
DoSomething();
}
reader.Read() never is read, my table is simple, have only attributes: cd_material(int), ds_material(varchar). And Exception not are triggered.
This query :
SELECT cd_material, ds_material FROM tbl_materiais WHERE ds_material = '%produto%'
Many rows are returned if in owner database ( sql management)
Related
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+"'";
?
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.
I need to execute the same query every second in GetStuff function, but after a minute or two Oracle throws ORA-00604 and runs out of cursors, I guess I need somehow to close open cursor after I return result. However I don't like the idea of re-connecting every time I need to query, my code is below:
public MyStuff GetStuff(string paramValue)
{
OracleCommand command = connection.CreateCommand();
command.CommandText = "select XXX from YY where param = ? ";
command.Parameters.Add(":param ", OracleDbType.Varchar2).Value = paramValue;
IDataReader reader = command.ExecuteReader();
while (reader.Read())
{
...
}
command.Dispose();
return stuff;
}
reader also needs to be disposed:
public MyStuff GetStuff(string paramValue)
{
using (OracleCommand command = connection.CreateCommand())
{
command.CommandText = "select XXX from YY where param = ? ";
command.Parameters.Add(":param ", OracleDbType.Varchar2).Value = paramValue;
using (IDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
...
}
}
return stuff;
}
}
Have a look at the using statement which is highly advised way to interact with IDisposables.
I need to execute the following command and pass the result to a label. I don't know how can i do it using Reader. Someone can give me a hand?
String sql = "SELECT * FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteReader();
As you can see i create the SQL statement and i execute it, but it does not work. Why?
The console says:
Cannot implicitly SqlDataReader to
String...
How can i get the desired results as String so the label can display it properly.
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT * FROM learer WHERE id = #id";
cmd.Parameters.AddWithValue("#id", index);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
}
It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:
String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();
Here is more information about Connecting to database and managing data.
ExecuteScalar() is what you need here
Duplicate question which basically says use ExecuteScalar() instead.
In some programming contexts getting a scalar value from a sql query is easy:
RowCount = Connection.Execute("SELECT Count(*) FROM TableA").Fields(0).Value
In C#, given a SqlConnection variable conn that is already open, is there a simpler way to do this same thing without laboriously creating a SqlCommand, a DataReader, and all in all taking about 5 lines to do the job?
SqlCommand has an ExecuteScalar method that does what you want.
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();
If you can use LINQ2SQL (or EntityFramework) you can simplify the actual query asking to
using (var context = new MyDbContext("connectionString"))
{
var rowCount = context.TableAs.Count();
}
If LINQ2SQL is an option that has lots of other benefits too compared to manually creating all SqlCommands, etc.
There is ExecuteScalar which saves you at least from the DataReader:
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
(Example taken from this MSDN documentation article)
You do not need a DataReader. This example pulls back the scalar value:
Object result;
using (SqlConnection con = new SqlConnection(ConnectionString)) {
con.Open();
using (SqlCommand cmd = new SqlCommand(SQLStoredProcName, con)) {
result = cmd.ExecuteScalar();
}
}
Investigate Command.ExecuteScalar:
using(var connection = new SqlConnection(myConnectionString))
{
connection.Open();
using(var command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = mySql;
var result = (int)command.ExecuteScalar();
}
}
If you're feeling really lazy, encapsulate it all in an extension method, like we do.
EDIT: As requested, an extension method:
public static T ExecuteScalar<T> (this SqlConnection connection, string sql)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if (string.IsNullOrEmpty(sql))
{
throw new ArgumentNullException("sql");
}
using(var command = connection.CreateCommand())
{
command.CommandText = sql;
command.CommandType = CommandType.Text;
return (T)command.ExecuteScalar();
}
}
Note, this version assumes you've properly built the SQL beforehand. I'd probably create a separate overload of this extension method that took two parameters: the stored procedure name and a List. That way, you could protect yourself against unwanted SQL injection attacks.