I'm trying to get the MAX value returned but it keeps returning 0.
string stateValue = "CA";
SqlCommand cmd = new SqlCommand("SELECT MAX(Population) FROM TestData WHERE State=" + stateValue);
cmd.Parameters.Add("#Population", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
DBConnection.Instance.execNonQuery(cmd);
int population = (int)cmd.Parameters["#Population"].Value;
In DBConnection class this is the execNonQuery function:
public int execNonQuery(string sCmd, CommandType cmdType)
{
SqlCommand cmd = new SqlCommand(sCmd, m_sqlDataBase);
cmd.CommandType = cmdType;
try
{
m_sqlDataBase.Open();
}
catch { }
return cmd.ExecuteNonQuery();
}
Parameter direction is used with Stored Procedures. Here you are simply executing a single query. You need to use SqlCommand.ExecuteScalar method, since you will only get back one result. It returns an object so you have to convert it to int before using it.
Also your code is using string concatenation to create SQL Query and it is prone to SQL Injection. Also consider using using statement with your Command and Connection.
using (SqlCommand cmd = new SqlCommand("SELECT MAX(Popluation) FROM TestData WHERE State=#state"))
{
//Associate connection with your command an open it
cmd.Parameters.AddWithValue("#state", stateValue);
int populuation = (int)cmd.ExecuteScalar();
}
The ExecuteNonQuery call does not return the result of executing your query.
You can use ExecuteScalar or Execute to get the value back.
public int execQuery(string sCmd, CommandType cmdType)
{
SqlCommand cmd = new SqlCommand(sCmd, m_sqlDataBase);
cmd.CommandType = cmdType;
try
{
m_sqlDataBase.Open();
return Convert.ToInt32(cmd.ExecuteScalar());
}
catch {
// handle your error but don't trap it here..
throw;
}
}
ExecuteScalar is a short-circuit for getting the first value, or the first result set. You can use it to return a single value out of a query, such as yours.
Another option is to use the Execute method to obtain a result set and then use that to get the value you're after:
public int execQuery(string sCmd, CommandType cmdType)
{
SqlCommand cmd = new SqlCommand(sCmd, m_sqlDataBase);
cmd.CommandType = cmdType;
try
{
m_sqlDataBase.Open();
using(var dataReader = cmd.Execute())
{
if (dataReader.Read())
{
return Convert.ToInt32(dataReader[0]);
}
}
}
catch {
// handle your error but don't trap it here..
throw;
}
}
How 'bout
var sql = string.Format("SELECT MAX(Popluation) FROM TestData WHERE State='{0}'", stateValue);
SqlCommand cmd = new SqlCommand(sql);
(The important part was adding the single quotes. The string.Format was to make it look pretty)
Related
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
using (var conexao = Conexao())
{
conexao.Open();
string rotaloja = Convert.ToString(dtExcel.Rows[i][1]) + Convert.ToString(dtExcel.Rows[i][0]);
string bn = "select * from Emb where ROTALOJ= #rotaloja";
OleDbCommand cmd1 = new OleDbCommand(bn, conexao);
cmd1.Parameters.AddWithValue("#rotaloja", rotaloja);
using (OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
using (OleDbDataReader drr = Queryyy.ExecuteReader())
{
if (drr.Read())
{
try
{
string cmdText = "UPDATE Emb SET ROTA=#p0, LOJA=#p1, QTDEEMBAL=#p2 where ROTALOJ= #rotaloja";
conexao.Open();
OleDbCommand cmd = new OleDbCommand(cmdText, conexao);
cmd.Parameters.AddWithValue("#p0", dtExcel.Rows[i][1]);
cmd.Parameters.AddWithValue("#p1", dtExcel.Rows[i][0]);
cmd.Parameters.AddWithValue("#p2", dtExcel.Rows[i][2]);
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("Error" + ex);
}
}
else
{
try
{
string cmdText = "INSERT INTO Emb (ROTALOJ , ROTA, LOJA, QTDEEMBAL) VALUES (#rotaloja,#p0,#p1,#p2)";
OleDbCommand cmd = new OleDbCommand(cmdText, conexao);
cmd.Parameters.AddWithValue("#p0", dtExcel.Rows[i][1]);
cmd.Parameters.AddWithValue("#p1", dtExcel.Rows[i][0]);
cmd.Parameters.AddWithValue("#p2", dtExcel.Rows[i][2]);
//////////////////////////////////////////////////////////////////////////////////////////////
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
}
}
I am doing import excel to database more when he does select to see if you have the information in the database is giving error can be? for those who help me thank you
Img : http://i.stack.imgur.com/qxQDm.png
You created a new query Queryyy and assumed that the parameters attached with previous query cmd1 would be available with your command string bn. You need to add parameter to your query Queryyy
using (OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
Query.Parameters.AddWithValue("#rotaloja", rotaloja); //here
using (OleDbDataReader drr = Queryyy.ExecuteReader())
//.......rest of your code
}
Consider using helpful variable names.
In your current code, you added parameter to a cmd1 which is independent of Queryyy. In your new query Queryyy, you are using command text which requires a parameter and since you are not passing it, you are getting the exception.
Take a look at : OleDbCommand.Parameters Property, You may have to pass the parameter with ?, since it doesn't seem to support named parameters.
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used.
You're not setting the value of #rotaloja in this query:
"UPDATE Emb SET ROTA=#p0, LOJA=#p1, QTDEEMBAL=#p2 where ROTALOJ= #rotaloja"
OleDBCommand does not support names parameters. Replace your parameters with ? in each SQL statement and add the parameters in the order that they appear in the query.
I am trying to use a SqlDataReader to run a query and then display the results in a messagebox, but I keep getting the error
Invalid attempt to read when no data is present.
Here is my code.
public void button1_Click(object sender, EventArgs e)
{
string results = "";
using (SqlConnection cs = new SqlConnection(#"Server=100-nurex-x-001.acds.net;Database=Report;User Id=reports;Password=mypassword"))
{
cs.Open();
string query = "select stationipaddress from station where stationname = #name";
using (SqlCommand cmd = new SqlCommand(query, cs))
{
// Add the parameter and set its value --
cmd.Parameters.AddWithValue("#name", textBox1.Text);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
label3.Text = dr.GetSqlValue(0).ToString();
results = dr.GetValue(0).ToString();
//MessageBox.Show(dr.GetValue(0).ToString());
//MessageBox.Show(results);
}
MessageBox.Show(results);
}
}
}
}
That's correct.
When you exit from the while loop the DataReader has reached the end of the loaded data and thus cannot be used to get the value of a non-existant current record.
The Read method advances the SqlDataReader (dr) to the next record and it returns true if there are more rows, otherwise false.
If you have only one record you could use the results variable in this way
MessageBox.Show(results);
Now, this will work because you have a TOP 1 in your sql statement, but, if you have more than one record, it will show only the value of the last record.
Also as noted by marc_s in its comment, if your table is empty, your code doesn't fall inside the while loop, so probably you could initialize the results variable with a message like:
results = "No data found";
EDIT: Seeing your comment below then you should change your code in this way
.....
// Use parameters **ALWAYS** -- **NEVER** cancatenate/substitute strings
string query = "select stationipaddress from station where stationname = #name";
using (SqlCommand cmd = new SqlCommand(query, cs))
{
// Add the parameter and set its value --
cmd.Parameters.AddWithValue("#name", textBox1.Text);
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
label3.Text = dr.GetSqlValue(0).ToString();
results = dr.GetValue(0).ToString();
}
}
}
.....
I ran into a similar issue trying to get a GUID I knew was there - I could run the same SQL directly in SQL Management Studio and get my result. So instead of trying to bring it back as a GUID (it was saved in a char(35) field, even though it really was a GUID!), I brought it back as a string, instead:
SqlConnection sqlConn = null;
string projId = String.Empty;
string queryString = "SELECT * FROM project WHERE project_name='My Project'";
try
{
sqlConn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(queryString, sqlConn);
sqlConn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
projId = reader.GetSqlValue(0).ToString(); // <-- safest way I found to get the first column's parameter -- increment the index if it is another column in your result
}
}
reader.Close();
sqlConn.Close();
return projId;
}
catch (SqlException ex)
{
// handle error
return projId;
}
catch (Exception ex)
{
// handle error
return projId;
}
finally
{
sqlConn.Close();
}
I'm very new to C#. I'm trying to retrieve the number of columns using:
SELECT count(*) FROM sys.columns
Could you please explain how to use the command and put it into a variable.
To connect to the database you can use the SqlConnection class and then to retrieve the Row Count you can use the Execute Scalar function. An example from MSDN:
cmd.CommandText = "SELECT count(*) FROM sys.columns;";
Int32 count = (Int32) cmd.ExecuteScalar();
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection
You will need to use ExecuteScalar as the others have said. Also, you will need to filter your SELECT on the object_id column to get the columns in a particular table.
SELECT count(*) FROM sys.columns WHERE object_id = OBJECT_ID(N'table_name')
Alternatively, you could do worse than familiarise yourself with the ANSI-standard INFORMATION_SCHEMA views to find the same information in a future-proof, cross-RDBMS way.
You have to use a command and retrieve back the scalar variable :
SqlCommand cmd = new SqlCommand(sql, conn);
Int32 count = (Int32)cmd.ExecuteScalar();
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"SELECT Count(*) from sys.columns";
// Specify the parameter value.
int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}",
reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
use Executescalar() for getting a single element.
using (SqlConnection con = new SqlConnection(ConnectionString)) //for connecting to database
{
con.Open();
try
{
using (SqlCommand getchild = new SqlCommand("select count(*) from table1 ", con)) //SQL queries
{
Int32 count = (Int32)getchild.ExecuteScalar();
}
}
}
Use ExecuteScalar
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.
Int32 colnumber = 0;
string sql = "SELECT count(*) FROM sys.columns";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
colnumber = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You'll want to use the ADO .NET functions in the System.Data.SqlClient namespace. ExecuteScalar is an easy-to-use method when you only want to get a single result. For multiple results, you can use a SqlDataReader.
using System.Data.SqlClient;
string resultVar = String.Empty;
string ServerName="localhost";
string DatabaseName="foo";
SqlConnection conn=new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI",ServerName,DatabaseName));
SqlCommand cmd=new SqlCommand(Query,conn);
try
{
conn.Open();
}
catch (SqlException se)
{
throw new InvalidOperationException(String.Format(
"Connection error: {0} Num:{1} State:{2}",
se.Message,se.Number, se.State));
}
resultVar = (string)cmd.ExecuteScalar().ToString();
conn.Close();
I'm wondering how to return the result from a SELECT COUNT statement in C#.
I have a sql statement that returns the count of 15.
Currently, I'm returning the datareader. Can I somehow return the result of that as a string?
static public SqlDataReader FillDataReader(string sql, SqlParameter[] parms)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = null;
conn.Open();
cmd.CommandTimeout = 120; //120 seconds for the query to finish executing
foreach (SqlParameter p in parms)
{
cmd.Parameters.Add(p);
}
try
{
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (SqlException ex)
{
if (dr != null)
{
dr.Close();
}
conn.Close();
//DBUtilExceptionHandler(ex, sql);
throw ex;
}
finally
{
}
return dr; //This could be null...be sure to test for that when you use it
}
Or I could use a different method. I just don't know what it should be.
Any help is appreciated.
This is my select statement:
select count(LeadListID) from LeadLists WHERE SalesPersonID = 1
AND LeadListDateCreated BETWEEN '9/1/11' AND '10/1/11 23:59:59'
Sure - just use:
int count = (int) query.ExecuteScalar();
// TODO: Decide the right culture to use etc
return count.ToString();
Notes:
Use using statements instead of manual try/catch/finally blocks
You should close the connection whether or not there was an error
Given that the natural result of the query is an integer, I would change it to return an int, not a string. Let the caller make that conversion if they want to
If there's an error, you should almost certainly let the exception bubble up, rather than returning null
I would write the code as:
public static int ExecuteScalarInt32(string sql, SqlParameter[] parms)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(sql, conn) { Parameters = parms })
{
conn.Open();
command.CommandTimeout = 120;
return (int) command.ExecuteScalar();
}
}
If you really needed a version to work on an arbitrary data reader, you could write it as:
public static T ExecuteQuery<T>(string sql, SqlParameter[] parms,
Func<SqlDataReader, T> projection)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(sql, conn) { Parameters = parms })
{
conn.Open();
command.CommandTimeout = 120;
return projection(command.ExecuteReader());
}
}
And then call it with:
int count = ExecuteQuery<int>(sql, parms, reader => {
if (!reader.MoveNext()) {
throw new SomeGoodExceptionType("No data");
}
return reader.GetInt32(0);
});
Sure, you can always call the ToString() method in .NET on the single field when reading it:
dr[0].ToString()
Are there many records that you want to concat as a string? Then you loop through each row, grab the value as a string, and create a master string in a for loop fashion.
Since you're expecting only a single value, a better alternative to ExecuteReader is the ExecuteScalar method:
try
{
var count = cmd.ExecuteScalar().ToString();
}
Either cast it as a varchar in your sql:
select cast(count(LeadListID) as varchar(10))
from LeadLists
WHERE SalesPersonID = 1
AND LeadListDateCreated BETWEEN '9/1/11' AND '10/1/11 23:59:59'
or just call .ToString() on the result, as shown in other answers.
Additionally, I'm not a fan of relying on CommandBehavior.CloseConnection for DataReaders. I much prefer code like this:
static public IEnumerable<IDataRecord> GetDataReader(string sql, SqlParameter[] parms)
{
using (var conn = new SqlConnection(ConnectionString))
using (var cmd = new SqlCommand(sql, conn))
{
cmd.CommandTimeout = 120; //120 seconds for the query to finish executing
foreach (SqlParameter p in parms)
{
cmd.Parameters.Add(p);
}
conn.Open();
using (var dr= cmd.ExecuteReader())
{
while (dr.Read())
{
yield return dr;
}
}
}
}
Use ExecuteScalar instead, that will return the first field from the first record of the returned recordset, which is what you want. That will return to you an object that is really an integer. Add a ToString to that and you should be good.
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.