I am developing a web application and in the code-behind, I need to get the ID column from specific table in the database and convert it to int. The query is:
string quizID = SELECT MIN(column_name) FROM table_name
and I want to put the value of it in
int quizid
which means I need to conversion, so how to do that?
You're going to want to do something like this:
using (SqlConnection conn=new SqlConnection(sql_string)) {
conn.Open();
SqlCommand command=new SqlCommand(
sql_query,
conn
);
Int32 quizid=((Int32?)command.ExecuteScalar()) ?? 0;
}
int quizID = -1;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
string cmdText = "SELECT MIN(column_name) FROM table_name";
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
while (reader.Read())
{
quizID = reader.GetInt32("columnname");
}
}
reader.Close();
}
conn.Close();
}
SqlCommand cmd = new SqlCommand("SELECT MIN(column_name) FROM table_name", conn);
try
{
conn.Open();
int quizid = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
conn is the SqlConnection object
Related
I'm displaying some data from the database into textboxes on my windows form and I have to add something else but it depends on the account type (that information is saved on my Databse). Meaning it is either DM (domestic) or CM(comercial). I want for it to charge an extra amount if it's CM.
I would appreciate any help, thank you.
OracleDataReader myReader = null;
OracleCommand myCommand = new OracleCommand("SELECT SUM(IMPORTE) AS corriente FROM MOVIMIENTOS WHERE CUENTA='"+txtIngreseCuenta3.Text + "'AND CONCEPTO=10", connectionString);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtCorriente.Text = (myReader["corriente"].ToString());
}
I'm using this code to display into the textbox but I want it to get the account type from another table and IF it's CM then add a certain amount into a textbox.
In your case I suggest that you use Execute Scalar instead of reader since you are returning only one value from the database. but in your case if you want this code to work you need to Cast the returned value into the correct dot net type and then populate the TextBox.
Example Using ExecuteReader
//txtCorriente.Text = ((int)myReader["corriente"]).ToString();
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtCorriente.Text = ((int)reader["corriente"]).ToString();
txtAnother.Text = ((decimal)reader["another"]).ToString();
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
}
Example Using ExecuteScalar
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;
}
I can't extract the values through a query and insert them into textboxes
Where am I going wrong?
Request.QueryString.Get("ID_Persona");
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM Persona WHERE ID = #id";
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID","");
cmd.Parameters.AddWithValue("#Nome", TextBox1.Text);
cmd.Parameters.AddWithValue("#Cognome", TextBox15.Text);
cmd.Parameters.AddWithValue("#Email", TextBox20.Text);
cmd.Parameters.AddWithValue("#CodiceFiscale", TextBox22.Text);
con.Open();
cmd.ExecuteNonQuery();
}
You need to use ExecuteReader to read values, something like this:
var connectionString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
string query = "SELECT ID,Nome,Cognome,Email,CodiceFiscale FROM Persona WHERE ID = #id";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#ID", Request.QueryString.Get("ID_Persona"));
con.Open();
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
//IDTextBox? = rdr["Id"].ToString(),
TextBox1.Text = rdr["Nome"].ToString(),
TextBox15.Text = rdr["Cognome"].ToString(),
TextBox20.Text= rdr["Email"].ToString(),
TextBox22.Text= rdr["CodiceFiscale"].ToString(),
}
}
}
}
You should use a ExecuteReader() instead of ExecuteNonQuery() since ExecuteNonQuery is meant for DML operations. Again, you need only the ID value to be passed then why you are passing unnecessary parameters to your query. Remove them all. An example below
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader["Email"]));
}
I can see several issues:
You should use ExecuteReader() instead of ExecuteNonQuery()
You should provide just 1 parameter - #ID; I doubt if it should have an empty value.
You should wrap IDisposable into using
Code:
string query =
#"SELECT ID,
Nome,
Cognome,
Email,
CodiceFiscale
FROM Persona
WHERE ID = #id";
using (SqlConnection con = new SqlConnection(...))
{
con.Open();
using SqlCommand cmd = new SqlCommand(query, con)
{
// I doubt if you want empty Id here.
// I've assumed you want to pass ID_Persona
cmd.Parameters.AddWithValue("#ID", Request.QueryString.Get("ID_Persona"));
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
TextBox1.Text = Convert.ToString(reader["Nome"]);
TextBox15.Text = Convert.ToString(reader["Cognome"]);
TextBox20.Text = Convert.ToString(reader["Email"]);
TextBox22.Text = Convert.ToString(reader["CodiceFiscale"]);
}
}
}
}
I am previously only familiar with Linq and the like for data access. I am working on something now that requires me to use actual SQL commands on the back end to return a single value. My code compiles and runs, however it is returning null for a value that I know should be returning something besides an empty string...
Is my structure off on this? Or is something else missing?
Below is my code:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
Here is a picture of the result set of the table:
Open the connection.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open(); //<- This line here.
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
cmd.ExecuteScalar() is probably throwing an InvalidOperationException because you haven't opened the connection. The exception is being caught, outputted to the console, then the initial value of newSex is begin returned since the call to ExecuteScalar threw.
ID is a int or varchar?
If is int use:
cmd.Parameters.Add("#sex", SqlDbType.Int).Value = sex;
instead of:
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
P.S.
Query parameters and parameter add into cmd.Parameters is case sensitive.
Write
#sex
instead of
#Sex
Figured it out. Had to open the cmd and close it AFTER I set the newSex variable to the value being pulled.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #Sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Connection = conn;
adapter.SelectCommand = cmd;
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
adapter.Fill(ds);
newSex = cmd.ExecuteScalar().ToString();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
}
Try this:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID" + sex;;
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
I am trying to take a single value from a database, but the cycle does not seem to start at all?
if (connection.State == ConnectionState.Open)
{
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
value = dataReader["amount"].ToString();
}
dataReader.Close();
connection.Close();
}
These are the commands:
public string value;
public static string Konekcija = "Server=127.0.0.1; Database=CardIgrica; Uid=admin; Pwd=admin;";
public string komanda = "SELECT amount FROM CardIgrica.creaures WHERE id = '1';";
MySqlConnection connection = new MySqlConnection(Konekcija);
MySqlCommand cmd = new MySqlCommand(komanda, connection);
connection.Open();
try this for the select
public string value {get; set;}
string komanda ="SELECT amount FROM CardIgrica.creaures WHERE id = 1";
Try this
using (SqlConnection conn = new SqlConnection(Konekcija))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clear();
cmd.CommandText = komanda ;
conn.Open();
var dataReader= cmd.ExecuteReader();
while (result.Read())
{
value = dataReader["amount"].ToString();
}
conn.Close();
}
If you need single value, you can use cmd.ExecuteScalar(); instead of cmd.ExecuteReader();
because ExecuteScalar() will return single value.
First open your sql connection then make object of MySqlCommand like below:
MySqlConnection connection = new MySqlConnection(Konekcija);
connection.Open();
MySqlCommand cmd = new MySqlCommand(komanda, connection);
Can anybody give an example for executing a T-SQL statement using C#?
Do you mean something like this:
private static void ReadOrderData(string connectionString)
{
string commandText = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
}
}
}
Or, perhaps something like:
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;
}
Source: MSDN
I suggest that you start with an ADO.NET turorial like this one
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson01.aspx
How to use SQLCommand
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson03.aspx
Using a reader:
SqlConnection MSSQLConn = new SqlConnection("your connection string");
MSSQLConn.Open();
SqlCommand MSSQLSelectConsignment = new SqlCommand();
MSSQLSelectConsignment.CommandText = "select * from yourtable where blah = #blah";
MSSQLSelectConsignment.Parameters.AddWithValue("#blah", somestring);
MSSQLSelectConsignment.Connection = MSSQLConnOLD;
SqlDataReader reader = MSSQLSelectConsignment.ExecuteReader();
while (reader.Read())
{
...
}
To bring back a single value:
MSSQLSelectConsignment.CommandText = "select fieldname from yourtable where blah = #blah";
string yourstring = MSSQLSelectConsignment.ExecuteScalar().ToString();
or to bring back number of rows affected for updates etc:
MSSQLSelectConsignment.CommandText = "update yourtable set yourfield = 0 where blah = #blah";
int yourint = MSSQLSelectConsignment.ExecuteNonQuery();
Hope helps :)