Id request from the database - c#

I'm trying to write the id request from the database. This is how I wrote it:
public int QueryId(String query)
{
var temp = this.connection;
MySqlCommand verifica = new MySqlCommand(query, connection);
var queryResult = verifica.ExecuteScalar();
return Convert.ToInt32(verifica.ExecuteScalar());
}
This is how I make use of the function:
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
nomeCorrente = reader.GetString("nome");
cognomeCorrente = reader.GetString("cognome");
idCorrente = db.QueryId("SELECT id FROM thewishlist.user WHERE email='" + user.Text + "'");
}
reader.Close();
db.CloseConnection();
It does not generate errors, but when I run the project and log out the user gives me the following error:
MySql.Data.MySqlClient.MySqlException There is already an open DataReader associated with this Connection which must be closed first.

The error is pretty clear. I suggest you make use of using statement and also since you're only returning one column you and use ExcecuteScalar instead of ExecuteReader. So your code will look something like:
var id = 0;
var query = "SELECT ID FROM thewishlist.user WHERE email = #email";
using (var con = new SqlConnection(this.connection))
{
using (var cmd = new SqlCommand(query, con))
{
con.Open();
cmd.Parameters.Add("#email", SqlDbType.NVarChar).Value = user.Text;
id = (int)cmd.ExecuteScalar();
}
}//connection will auto close here and object will get disposed
return id;
Also to prevent sql injection you should always use paramertised sql queries.

As Jason said that, you should close the reader firstly, then call db.QueryId to execute the new query, I modifed your code as follows:
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
nomeCorrente = reader.GetString("nome");
cognomeCorrente = reader.GetString("cognome");
}
reader.Close();
}
idCorrente = db.QueryId("SELECT id FROM thewishlist.user WHERE email='" + user.Text + "'");
db.CloseConnection();

Related

Remove red underline: GetDepartmentsByDepartmentID

public MyUniversity GetDepartmentsByDepartmentID(string department)
{
string query = "SELECT * FROM Departments WHERE DepartmentID ='" + department + "'";
SqlConnection connection = new SqlConnection(dbConnection);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
MyUniversity deprtmnt = new MyUniversity();
while (reader.Read())
{
deprtmnt.code = reader["Code"].ToString();
deprtmnt.title = reader["title"].ToString();
deprtmnt.credit = reader["Credit"].ToString();
deprtmnt.description = reader["Description"].ToString();
deprtmnt.semester = reader["Semester"].ToString();
reader.Close();
connection.Close();
return deprtmnt;
}
}
Your error is that not all code path return value. Reason is that in the scope of your loop:
while (reader.Read())
{
/* Code */
return deprtmnt;
}
If code doesn't enter while loop then there is no return statement.
move the return to be outside of the loop's scope:
MyUniversity deprtmnt = new MyUniversity();
while (reader.Read())
{
/* Code */
}
return deprtmnt;
Read about parameterized queries as using string concatenation for sql queries is susceptible for sql-injections
Why do we always prefer using parameters in SQL statements?

C# Windows 8.1 / Get SQLite string query result as variable

How to get the result of this SQLite query result in variable?
I need to access this in my Windows 8.1 application.
string queryDB = string.Format("Select * from ContryLookup");
var tempcountryLookUpData = connection.Execute(queryDB);
Thanks
You will need reference to SqliteDataReader
static void Main()
{
string cs = "URI=file:test.db";
using(SqliteConnection con = new SqliteConnection(cs))
{
con.Open();
string stm = "Select * from ContryLookup";
using (SqliteCommand cmd = new SqliteCommand(stm, con))
{
using (SqliteDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Console.WriteLine(rdr.GetInt32(0) + " "
+ rdr.GetString(1) + " " + rdr.GetInt32(2));
}
}
}
con.Close();
}
}
Credits
Worth mentioning
Do you have an execute procedure called Execute??
One way to do what you want is using the ExecuteReader procedure and return that to a DataReader object. Then use a for loop to traverse the data:
string sql = "select * from table";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
Console.WriteLine(reader["columnName"]);

How can I get SQL result into a STRING variable?

I'm trying to get the SQL result in a C# string variable or string array. Is it possible? Do I need to use SqlDataReader in some way?
I'm very new to C# functions and all, used to work in PHP, so please give a working example if you can (If relevant I can already connect and access the database, insert and select.. I just don't know how to store the result in a string variable).
This isn't the single greatest example in history, as if you don't return any rows from the database you'll end up with an exception, but if you want to use a stored procedure from the database, rather than running a SELECT statement straight from your code, then this will allow you to return a string:
public string StringFromDatabase()
{
SqlConnection connection = null;
try
{
var dataSet = new DataSet();
connection = new SqlConnection("Your Connection String Goes Here");
connection.Open();
var command = new SqlCommand("Your Stored Procedure Name Goes Here", connection)
{
CommandType = CommandType.StoredProcedure
};
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataSet);
return dataSet.Tables[0].Rows[0]["Item"].ToString();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
It can definitely be improved, but it would give you a starting point to work from if you want to go down a stored procedure route.
Try This:
SqlConnection con=new SqlConnection("/*connection string*/");
SqlCommand SelectCommand = new SqlCommand("SELECT email FROM table1", con);
SqlDataReader myreader;
con.Open();
myreader = SelectCommand.ExecuteReader();
List<String> lstEmails=new List<String>();
while (myreader.Read())
{
lstEmails.Add(myreader[0].ToString());
//strValue=myreader["email"].ToString();
//strValue=myreader.GetString(0);
}
con.Close();
accessing the Emails from list
lstEmails[0]->first email
lstEmails[1]->second email
...etc.,
You could use an SQL Data Reader:
string sql = "SELECT email FROM Table WHERE Field = #Parameter";
string variable;
using (var connection = new SqlConnection("Your Connection String"))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#Parameter", someValue);
connection.Open();
using (var reader = command.ExecuteReader())
{
//Check the reader has data:
if (reader.Read())
{
variable = reader.GetString(reader.GetOrdinal("Column"));
}
// If you need to use all rows returned use a loop:
while (reader.Read())
{
// Do something
}
}
}
Or you could use SqlCommand.ExecuteScalar()
string sql = "SELECT email FROM Table WHERE Field = #Parameter";
string variable;
using (var connection = new SqlConnection("Your Connection String"))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#Parameter", someValue);
connection.Open();
variable = (string)command.ExecuteScalar();
}
This May help you For MySQL
MySqlDataReader reader = mycommand.ExecuteReader();
while (reader.Read())
{
TextBox2.Text = reader.ToString();
}
For SQL
using (SqlCommand command = new SqlCommand("*SELECT QUERY HERE*", connection))
{
//
// Invoke ExecuteReader method.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
TextBox2.Text = reader.GetString(0);
}
}
Try this:
public string SaveStringSQL(string pQuery, string ConnectionString)
{
var connection = new Conexao(ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand(pQuery, connection.Connection);
var SavedString = (string)command.ExecuteScalar();
connection.Close();
return SavedString;
}
The ExecuteScalar function saves whatever type of data there is on your database - you just have to specify it.
Keep in mind that it can only save one line at a time.

Get value from database not behaving as expected

I'm making an asp.net application, I'm trying to read data from sql tables, but data just wont compare, as I don't get the message "You don't have a bank account, you can't register to our website"
SqlConnection connection = new SqlConnection(#"Data Source=SHKELQIM\SQLEXPRESS;Initial Catalog=E-Banking;Integrated Security=True");
connection.Open();
SqlDataReader reader = null;
SqlCommand command = new SqlCommand("SELECT * FROM ACCOUNTS WHERE Accountnumber='" + accountnumber1.Text + "'", connection);
reader = command.ExecuteReader();
if (reader.Read())
{
string getAccountNumber = reader[0].ToString();
reader.Close();
if (getAccountNumber != accountnumber1.Text)
{
lblaccountnumber.Visible = true;
lblaccountnumber.Text = "You don't have a bank account, you can't register to our website";
}
}
The best way to find this issue is to put a break point on the line:
if (getAccountNumber != accountnumber1.Text)
and see why the values do not match.
My guess is that account number is not the first column in your SELECT * query, thus reader[0].ToString() is not really the account number, but another value. Instead get the column index via the column name, like this:
string getAccountNumber = reader.GetString(reader.GetOrdinal("Accountnumber"));
It would also be a great idea to use a parameterized query so you do not get a visit from Little Bobby Tables.
Here is your code using a parameterized query:
string theQuery = "SELECT * FROM ACCOUNTS WHERE Accountnumber=#AccountNumber";
SqlCommand command = new SqlCommand(theQuery, connection);
command.Parameters.AddWithValue("#AccountNumber", accountnumber1.Text);
reader = command.ExecuteReader();
I would check reader.HasRows property and show the message
using (SqlConnection connection = new SqlConnection(#"Data Source=SHKELQIM\SQLEXPRESS;Initial Catalog=E-Banking;Integrated Security=True"))
using(SqlCommand command = new SqlCommand("SELECT * FROM ACCOUNTS WHERE Accountnumber= #Accountnumber", connection))
{
command.Parameters.AddWithValue("Accountnumber", accountnumber1.Text);
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
if (!reader.HasRows)
{
lblaccountnumber.Visible = true;
lblaccountnumber.Text = "You don't have a bank account, you can't register to our website";
}
}
}

Error with OracleDataReader. Error: Invalid operation. The connection is closed

When I try to assign the reader C# throws an exception:
Invalid operation. The connection is closed
I try to get a result from a query that returns a single cell with an average value inside.
cmd is an oraclecomand that i use to insert a row into a table and so far so good. I see the message box next and after that the exception appears.
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Recipe Rated");
OracleCommand cm = new OracleCommand("select round(avg(rating),1) from rates where id_rec = "+id);
OracleDataReader reader = cm.ExecuteReader();
reader.Read();
textBox5.Text =""+reader.GetInt16(0);
}
You should open the connection and you should also use sql-parameters. Hopefully this is the correct oracle syntax because i cannot test it:
using(var con = new OracleConnection("ConnectionString Here"))
using(var cmd = new OracleCommand("ADD YOUR INSERT/UPDATE/DELETE", con))
{
con.Open();
cmd.ExecuteNonQuery();
using (var cm = new OracleCommand("select round(avg(rating),1)As AvgRating from rates where id_rec = #id", con))
{
cm.Parameters.AddWithValue("#id", id);
using (var reader = cm.ExecuteReader())
{
if (reader.Read())
{
textBox5.Text = reader.GetInt16(0).ToString();
}
}
}
}
Note that i have used the using-statement to ensure that all unmanaged resources are disposed as soon as possible. It also closes connections (even on error).
Edit: Since you are selecting just a single value i suggest to use ExecuteScalar:
using (var cm = new OracleCommand("select round(avg(rating),1)As AvgRating from rates where id_rec = #id", con))
{
cm.Parameters.AddWithValue("#id", id);
object avgRating = cm.ExecuteScalar();
if (!(avgRating is DBNull))
{
textBox5.Text = avgRating.ToString();
}
}
When you use `OracleCommand', you have to associate a valid OracleConnection object to it.
using (OracleConnection connection = new OracleConnection(connectionString))
{
MessageBox.Show("Recipe Rated");
OracleCommand cm = new OracleCommand("select round(avg(rating),1) from rates where id_rec = "+id);
try
{
cm.Connection = connection;
connection.Open(); //oracle connection object
OracleDataReader reader = cm.ExecuteReader();
reader.Read();
textBox5.Text =""+reader.GetInt16(0);
}
}
Hope this help.
Thanks.

Categories