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
}
}
Related
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
}
}
I'm coding a simple application using c# asp.net. I'm getting the averages of columns. How can I get the individual values from the result and display it in a new label (label1, label2, label3....)?
I tried ExecuteScalar().ToString(); but it returns only the first column.
Below is my code:
SqlConnection con;
con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\STATDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand com = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
string result = "SELECT AVG(p_tan) AS p_tang, AVG(e_tan) AS e_tang, AVG(p_rel) AS p_reli FROM statistics";
SqlCommand showresult = new SqlCommand(result, con);
con.Open();
Label1.Text = showresult.ExecuteScalar().ToString();
//Label2.Text = p_tang
//Label3.Text = e_tang
//Label4.Text = p_reli
con.Close();
Any help will be appreciated.
Use showresult.ExecuteReader() and then iterate over the row to get the values
SqlDataReader reader=showresult.ExecuteReader();
while (reader.Read())
{
Label1.Text= reader["p_tang"].ToString().Trim();
Label2.Text= reader["e_tang"].ToString().Trim();
Label3.Text= reader["p_reli"].ToString().Trim();
}
ExecuteScalar will only pull one value. You will need do either use a DataReader or DataAdapter to get multiple values from the database.
I want to run an insert query in C#, which has multiple parameters. I just want to have a for loop, so that it goes through all parameters and assign a value to that parameter.
Query is in access database.
public static bool SubmitData(string queryName)
{
OleDbConnection conn = new OleDbConnection(cnnString);
OleDbCommand cmd = new OleDbCommand(queryName, conn);
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string strParameterName;
conn.Open();
cmd = new OleDbCommand(queryName, conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = queryName;
for (int i = 0; i < cmd.Parameters.Count; i++)
{
}
conn = null;
return true;
}
Above example has 3 parameters, but count is coming up as 0.
I really fail to see where are the three parameters. Parameters.Count does not return the number of parameters your procedure receiver. It returns the count for the already added parameters.
What you probably want is:
cmd.Parameters.Add("#p1", OleDbType.Type1).Value = value1;
cmd.Parameters.Add("#p2", OleDbType.Type2).Value = value2;
Parameters is the parameter collection, initially empty. The method Add, add the parameter, and the Value property assign it's value.
Note that in OleDbConnection, the order of the parameter matters, so you need to know before hand the order from the query.
string sql = "Select UserId From User where UserName='Gheorghe'";
SqlCommand cmd=new SqlCommand(sql, connection);
cmd.ExecuteScalar(); //this statement return 0
but I want to get the id of user?
how can I get it?
You need the SqlDataReader.
SqlDataReader Provides a way of reading a forward-only stream of rows from a SQL Server database.
Sample
string sql = "Select UserId From User where UserName='Gheorghe'";
SqlCommand cmd=new SqlCommand(sql, connection);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) {
rd.Read(); // read first row
var userId = rd.GetInt32(0);
}
More Information
MSDN - SqlDataReader Class
Simply cast the returned value:
int userId = (Int32)cmd.ExecuteScalar();
But be aware that ExecuteScalar will return null if your query returns an empty result set, and in that case the above code snippet will throw an InvalidCastException.
try with select TOP 1 and ExecuteScalar
string sql = "Select TOP 1 UserId From User where UserName='Gheorghe'";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
var result = (Int32)cmd.ExecuteScalar();
}
}
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