So i have code that can call a string from database that works perfectly for my label but when i try to call an integer it doesn't work. How can i reformat the code below to work for an integer?
string MoneySaved = null;
string sql = "Select Distinct(Tester) From VExecutionGlobalHistory Where Tester = 'strUserName'";
string connString = "myconnectionstringgoeshere";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(sql, conn))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
MoneySaved = reader[0] as string;
MoneySavedLabel.Text = MoneySaved;
//break for single row or you can continue if you have multiple rows...
break;
}
}
conn.Close();
}
Here is what worked:
string MoneySaved = null;
string sql = "Select Distinct(Tester) From VExecutionGlobalHistory Where Tester = 'strUserName'";
string connString = "myconnectionstringgoeshere";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(sql, conn))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
MoneySaved = reader[0].ToString();
MoneySavedLabel.Text = MoneySaved;
//break for single row or you can continue if you have multiple rows...
break;
}
}
conn.Close();
}
Related
I am intending to perform a call to ExecuteNonQuery() while the SqlDataReader is opened.
Code:
string commandString = "" //command string
using (SqlDataReader reader = cmd2.ExecuteReader())
{
while (reader.Read())
{
string temp = Convert.ToString(reader["RequestID"]);
string date;
using (SqlCommand cmd3 = new SqlCommand(commandString, con))
{
date = Convert.ToString(cmd3.ExecuteScalar());
}
}
}
I tried executing this but I got the error:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
There is already an open DataReader associated with this Command which must be closed first.
I have the MultipleActiveResultSets set to True in the connection string. May I know if it is possible to do it?
While MARS should work, it's usually not the best choice. Simply load the results of the first query into a DataTable and iterate the rows.
var dt = new DataTable();
using (SqlDataReader reader = cmd2.ExecuteReader())
{
dt.Load(reader);
}
foreach (DataRow row in dt.Rows)
{
string temp = Convert.ToString(row["RequestID"]);
string date;
SqlCommand cmd3 = new SqlCommand(commandString, con)
date = Convert.ToString(cmd3.ExecuteScalar());
}
You need to add MultipleActiveResultSets in your connection string, though you already added. Try below code that's executed successfully,
string conStr = "Data Source=DB_SERVER;Initial Catalog=DB_NAME;User Id=userId; Password=password;MultipleActiveResultSets=True";
using (SqlConnection con = new SqlConnection(conStr)) {
try {
con.Open();
string commandText = #"Select Id from Table1";
string commandText1 = #"Select CreatedDate FROM Table2 Where table1_Id = #table1_Id";
SqlCommand sqlCommand = new SqlCommand(commandText, con);
var dataReader = sqlCommand.ExecuteReader();
string date;
while (dataReader.Read()) {
var vId = dataReader["Id"].ToString();
var sqlCommand1 = new SqlCommand(commandText1, con);
sqlCommand1.Parameters.AddWithValue("#table1_Id", vId);
date= sqlCommand1.ExecuteScalar().ToString();
}
con.Close();
} catch (Exception ex) {
//Handle Exception
}
}
I would like to get some help : I can't get values form SQL Database to WPF textbox.
I tried by myself many codes that didn't worked, and this one looks fine but ".ToString" argument is wrong.
What should i put instead ?
using (SqlConnection con = new SqlConnection(MyConnString))
{
SqlCommand sqlCmd = new SqlCommand("SELECT DATE_A FROM Donnees_Accueil", con);
con.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
hourA.Text = sqlReader["Date_A"].ToString;
}
sqlReader.Close();
}
Thank you in advance,
Zancrew.
Well, ToString() is a method, not property, that's why () is required; if you want to concat all the records:
using (SqlConnection con = new SqlConnection(MyConnString))
{
con.Open();
using (SqlCommand sqlCmd = new SqlCommand("SELECT DATE_A FROM Donnees_Accueil", con))
{
using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (sqlReader.Read())
{
sb.Append(Convert.ToString(sqlReader["Date_A"]));
}
hourA.Text = sb.ToString();
}
}
}
If you want to get the 1st record only:
using (SqlConnection con = new SqlConnection(MyConnString))
{
con.Open();
using (SqlCommand sqlCmd = new SqlCommand("SELECT DATE_A FROM Donnees_Accueil", con))
{
using (SqlDataReader sqlReader = sqlCmd.ExecuteReader())
{
if (sqlReader.Read())
hourA.Text = Convert.ToString(sqlReader["Date_A"]);
else
hourA.Text = "";
}
}
}
I want to set eurvalue variable equal to the value of the first cell from AvailableMoney table , column EUR
I have tried this
float eurvalue;
string connectionString = #"Data Source=C:\Users\FluksikartoN\Documents\BFDB.sdf;Password=Corocoro93!";
string sql = "SELECT EUR FROM AvailableMoney";
using (SqlCeConnection conn = new SqlCeConnection(connectionString))
{
conn.Open();
using (SqlCeCommand cmd = new SqlCeCommand(sql, conn))
{
eurvalue = (float)cmd.ExecuteScalar();
//cmd.Parameters.AddWithValue("#valueeur", value);
// cmd.ExecuteNonQuery();
}
}
label2.Text = eurvalue.ToString();
It is all about robust error and null checking.
Incidentally, float is generally a poor data type for currency/money because it loses precision. I don't know what SQL Server CE offers but use a decimal type instead if you can.
using (SqlCeCommand cmd = new SqlCeCommand(sql, conn))
{
object val = cmd.ExecuteScalar();
if(val != null)
{
if(float.TryParse(val.ToString(), out eurvalue))
{
label2.Text = eurvalue.ToString();
}
}
}
Use ExecuteReader instead ExecuteScalar. The method ExecuteReader returns a SqlCeDataReader which allows reading a forward-only stream of rows from a data source.
float eurvalue = 0.0f;
string connectionString = #"Data Source=C:\Users\FluksikartoN\Documents\BFDB.sdf;Password=Corocoro93!";
string sql = "SELECT TOP 1 EUR FROM AvailableMoney";
using (SqlCeConnection conn = new SqlCeConnection(connectionString))
{
conn.Open();
using (SqlCeCommand cmd = new SqlCeCommand(sql, conn))
{
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
{
eurvalue = reader.GetFloat(0);
}
}
}
}
label2.Text = eurvalue.ToString();
I have a SQL query. Just i want to check query returning a values or not using c#. Can any one help on this to fix it. Thanks in advance.
Sqlcommand cmd = new Sqlcomman("select Name from Engdetails",con)
if (query != 0)
{
some coding..
}
else
{
coding...
}
SqlCommand cmd = new SqlCommand("select Name from Engdetails",con)
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
// The command returns Row(s)
}
else
{
// No Row has been returned.
}
There are a number of ways to work with sqlCommand; some examples:
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
...
or
using (SqlCommand cmd = new SqlCommand(query, connection))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(data);
}
if it has data, the data will be in data.Tables
SqlCommand cmd = new SqlCommand("select Name from Engdetails", con);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
// somecoding
}
else
{
// somecoding
}
a example in this case rdr.GetString is Name value of the query.
using (MySqlConnection conn = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
MySqlDataReader rdr = null;
string[] dados_bd = new string[2];
conn.Open();
cmd.Connection = conn;
cmd.CommandText = sql;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (estado == 1)
{
dados_bd[0] = rdr.GetString(0);
cmd.ExecuteNonQuery();
For the UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the SQL statement.
For all other types of statements, the return value is -1.
It's easy to bind a data source to something like a gridview or repeater, but how would I do it with a label? Heres the sql connection that I want to modify. By the way, I don't need 2 way binding.
public void Sql_Connection(string queryString)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The query I'm using:
SELECT Description FROM RbSpecials WHERE Active=1
public string SqlConnection(string queryString)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = queryString;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// This will return the first result
// but there might be other
return reader.GetString(0);
}
}
return null;
}
}
This will also ensure that in case of exception all disposable objects are disposed and will properly return the SQLConnection to the connection pool in order to be reused.
And finally assign the Text property of the label:
lblTest.Text = SqlConnection("SELECT Description FROM RbSpecials WHERE Active=1");
use ExecuteReader rather than ExecuteNonQuery
public void Sql_Connection(string queryString)
{
using(SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings"RBConnectionString"].ConnectionString))
{
using(SqlCommand cmd = new SqlCommand(queryString, conn))
{
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
lblDescription.Text = rdr.GetString(0);
}
}
}
}
}
using (SqlConnection con = new SqlConnection(Connection_String))
{
SqlCommand cmd = new SqlCommand("select * from Customers", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader adpt = cmd.ExecureReader();
if(rdr.Read())
{
lblName.Text = rdr[0].ToString();
}
}