I'm not very good but I'm trying. I think there is something I don't understand somewhere...
I'm trying to get statistique from a DB like how many row got "X". Look simple. I know the SQL statement for it. There is a lot of walkthrough around. But I don't know how to make it appear on a page.
if(!Request.QueryString["RNum"].IsEmpty() ) {
searchTerm = Request.QueryString["RNum"];
selectCommand2 = "SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl = #0";
}
var Count = db.QueryValue(selectCommand2, searchTerm);
With a submit button to send the query how can I make it appear on a page?
just try this
searchTerm = Request.QueryString["RNum"];
string sqlSelect = "SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl= #NoEmpl";
SqlConnection sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand(sqlSelect, sqlConnection);
// Set SqlDbType based on your DB column Data-Type
sqlCommand.Parameters.Add("#NoEmpl", System.Data.SqlDbType.Varcahr);
sqlCommand.Parameters["#NoEmpl"].Value = searchTerm ;
OR
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT COUNT(NoEmpl) FROM DTool Where NoEmpl= #NoEmpl", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("#NoEmpl", searchTerm ));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
//read here
}
}
Related
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)
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connecton1"].ConnectionString);
conn.Open();
SqlCommand check = new SqlCommand("SELECT Location FROM Items WHERE Serial="+Convert.ToInt32(Serialtxt.Text).ToString()+"", conn);
string checker = check.ExecuteReader();
I'm trying to look for a piece of data in my database and assign it to a variable. The error I get is
Cannot implicitly convert type 'System.Data.SqlClient.SqlDataReader' to string
What am I doing wrong?
You have to use ExecuteScalar instead.
string checker = (string)check.ExecuteScalar();
You should also use sql-parameters to prevent sql-injection.
SqlCommand check = new SqlCommand("SELECT Location FROM Items WHERE Serial = #Serial", conn);
check.Parameters.AddWithValue("#Serial", Convert.ToInt32(Serialtxt.Text));
If you instead expect multiple rows per serial you can use ExecuteReader and fill a List<string>:
List<string> allLocations = new List<string>();
using(SqlDataReader rd = check.ExecuteReader())
while(rd.Read())
allLocations.Add(rd.GetString(0));
change the checker type from string to SqlDataReader
then you could do
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connecton1"].ConnectionString);
conn.Open();
SqlCommand check = new SqlCommand("SELECT Location FROM Items WHERE Serial ="+Convert.ToInt32(Serialtxt.Text).ToString()+"", conn);
SqlDataReader checker = check.ExecuteReader();
while (checker.Read())
{
if (checker[0] != null)
{
//some logic with the result
}
}
First of all.. excuse me for my bad English , i hope to be understood.
I'm regullar to work with LINQ , the SQL is new for me.
i'm trying to do the next thing: i have the next method on c#:
public string niceMethod()
{
SqlConnection connection = new SqlConnection("Data Source=*******;Integrated Security=False;");
string commandtext = "SELECT bla FROM items WHERE main = 1";
SqlCommand command = new SqlCommand(commandtext, connection);
connection.Open();
string tDate = (string)command.ExecuteScalar();
connection.Close();
return tDate;
}
I have page for example: items.aspx?nID=144
how can i do that the SELECT command will be with querystring and that will take the value
from the "items" table by the id (nID) that show on the address ?
The table have the design for example:id, title, bla, main.
Try something like this:
int nID = int.Parse(Request.QueryString["nID"].ToString());
niceMethod(nID);
public string niceMethod(int nID)
{
using (var conn = new SqlConnection("Data Source=server;Initial Catalog=blah;Integrated Security=False;"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = #"SELECT bla, id, title FROM items WHERE main = #nID";
cmd.Parameters.AddWithValue("#nID", nID);
string tDate = cmd.ExecuteScalar().ToString();
return tDate;
}
}
Try this:
Pay attention to the (Request.QueryString["nID"] ?? "0").ToString() it's really importent so you wont get exception when there is no query.
public string niceMethod()
{
string tDate = "";
string ID = (Request.QueryString["nID"] ?? "0").ToString(); // Get's the nID query, incase there is no query, returns 0.
using (SqlConnection connection = new SqlConnection("Data Source=*******;Integrated Security=False;"))
{
string commandtext = "SELECT bla FROM items WHERE id=#ID"; //#ID Is a parameter
SqlCommand command = new SqlCommand(commandtext, connection);
command.Parameters.AddWithValue("#ID", ID); //Adds the ID we got before to the SQL command
connection.Open();
tDate = (string)command.ExecuteScalar();
} //Connection will automaticly get Closed becuase of "using";
return tDate;
}
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.
On my current project, to get a single value (select column from table where id=val), the previous programmer goes through using a datarow, datatable and an sqldatadapter (and of course sqlconnection) just to get that one value.
Is there an easier way to make a simple select query? In php, I can just use mysql_query and then mysql_result and I'm done.
It would be nice if I could just do:
SqlConnection conSql = new SqlConnection(ConnStr);
SomeSqlClass obj = new SomeSqlClass(sql_string, conSql);
conSql.Close();
return obj[0];
Thanks for any tips.
You can skip the DataReader and the DataAdapter and just call ExecuteScalar() on the sql command.
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM whatever
WHERE id = 5", conn);
try
{
conn.Open();
newID = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You are probably looking for SqlCommand and SqlDataReader
Dictionary<int, string> users = new Dictionary<int, string>();
using(SqlConnection connection = new SqlConnection("Your connection string"))
{
string query = "SELECT UserId, UserName FROM Users";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
users.Add(reader.GetInt32(0), reader.GetString(1));
}
connection.Close();
}
Actually, there is a method SqlCommand.ExecuteScalar() that will simply return the first field from the first row of the returned results. Just for you.
.NET Framework Class Library
SqlCommand..::.ExecuteScalar Method
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
You can do something very similar:
using (SqlConnection conn = new SqlConnection(ConnStr))
using (SqlCommand cmd = new SqlCommand(sql_string, conn))
{
conn.Open();
return cmd.ExecuteScalar();
}
you can use SqlCommands executeScalar function. Please look at the following link
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx