MySqlCommand in Asp.net WEB Forms to Display in Label - c#

i have this sql command
string myreg = "select registration_no from truck where truck_id ='" + truckID + "'";
MySqlCommand cmd = new MySqlCommand(myreg, conn);
i want to put the value of myreg to my RegistrationNo.Text label.
i have this RegistrationNo.Text = myreg; and it displays select registration_no from truck where truck_id on my page

You need to read something about the workings of ADO.NET and its providers.
To get the result of that query in your textbox you need
Open a connection to your MySql Server
Prepare a command to send to the Server
Get back the result
Write the result to your textbox
All these passages requires the use of specific classes and some code to glue everything together
// Prepare your command using a parameter placeholder
string myreg = "select registration_no from truck where truck_id =#id";
// Build the connection to the server and build the command to execute
using (MySqlConnection cnn = new MySqlConnection(.... the connection string that identifies your server and db ))
using (MySqlCommand cmd = new MySqlCommand(myreg, cnn))
{
// Open the connection
cnn.Open();
// Add the parameter expected
cmd.Parameters.Add("#id", MySqlDbType.VarChar).Value = truckID;
// Execute the command and get back the return value (if found)
object result = cmd.ExecuteScalar();
// Check if the ExecuteScalar has returned something
if(result != null)
RegistrationNo.Text = result.ToString();
else
... message to your user about the failed search ...
}
PS. I have assumed that your variable truckID is a string because in your original code you have passed it between single quotes, but if it is an integer then you need to modify the parameter type to MySqlDbType.Int32
Also, I have used the ExecuteScalar method instead of ExecuteReader because I think that your query returns just a row with a single column and for this task it is better to use ExecuteScalar

You can use datareader also.See MSDN documentation here.
using (connection)
{
SqlCommand command = new SqlCommand(
"SQL Query",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}

Related

reading data with OleDbDataReader

I'm trying to get the value of a Field (User Access level it's 1 or 2 in string format) after login
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dsms.accdb");
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT AL From Users WHERE Username='" + textusername.text + "'", connection);
reader = command.ExecuteReader();
if( reader.HasRows)
{
MessageBox.Show("success","status");
label1.Text = reader.GetString(1);
}
else
MessageBox.Show("failur", "status");
connection.Close();
I did execute the code in Access and it's was totally fine
but in the program, it says "No data exist for the row/column"
The main problem in your code is the fact that you need to call reader.Read() to get anything out from a DataReader. Just calling HasRows doesn't position the reader on the first record of your query.
There are other problems in your code.
Disposable objects like connections, commands and readers should be created in a using statement to ensure proper disposition after use and because you have only one field in your query, you should use the index 0 to retrieve it not 1.
Finally the most important one. You should NEVER concatenate strings to build an sql query. In this way a malicious user could write anything in your textbox, even valid sql commands that could be executed against your database. It is called Sql Injection and if you search for these terms you will find very detailed discussions about it. However, to avoid this problem (and others like parsing input with apostrophes) you use a parameterized query like below.
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand command = new OleDbCommand("SELECT AL From Users WHERE Username=#name", connection);
{
connection.Open();
command.Parameters.Add("#name", OleDbType.VarWChar).Value = txtusername.text;
using(OleDbDataReader reader = command.ExecuteReader())
{
if( reader.Read())
{
MessageBox.Show("success","status");
label1.Text = reader.GetString(0);
}
else
MessageBox.Show("failur", "status");
}
}

How to fix MySqlCommand AddWithValue() Not Assigning Parameters

Want to send a Select MySqlCommand query but the AddWithValue() method doesn't assign given parameters their values. Therefor I'm unable to get the right data from database.
I've already tried changing # symbol to ?
I've also tried Command.Parameters.AddWithValue("param1", textbox1.text);
I removed all the unnecessary apostrophes.
I tried to prepare the command before and after assigning parameters.
#define debug
Database_Interface db = new Database_Handler();
public string GetIDFromDB(string user)
{
using(MySqlConnection conn = db.Connection)
{
db.OpenConnection(conn);
string sql = "SELECT ID FROM Users WHERE USERNAME = #User";
using (MySqlCommand cmd = new MySqlCommand(sql,conn))
{
cmd.Parameters.AddWithValue("#User", user);
cmd.Prepare();
#if debug
return cmd.CommandText;
#endif
MySqlDataReader rdr = cmd.ExecuteReader();
db.Connection.Close();
if (rdr.HasRows)
{
rdr.Read();
return rdr.GetString("ID");
}
else
return "inv_user";
}
}
}
What the debug return, returns is the same sql with no params actually assigned. However when I've tried to do it the very basic way put the user var inside the sql it works as it should. The only problem is with AddWithValue().

Error with SQLDataReader

C#, Razor
my code is:
#using (SqlConnection Praktikum2 = new SqlConnection("Data Source=Mark\\SQLEXPRESS;Initial Catalog=Connection;Integrated Security=True"))
{
using(connection)
{
SqlCommand command = new SqlCommand("SELECT KategoryID FROM Kategory WHERE Name = " + Request.Params["kategory"]);
connection.Open();
SqlDataReader reader = command.ExecuteReader(); //ERROR!!!
while (reader.Read())
{
string ID = reader["KategorieID"].ToString() ;
Console.WriteLine("ID = {0}", ID);
}
reader.Close();
};
}
i get an error that there's a wrong syntax near "=".
how can i solve this?
The problem is caused by the missing quotes around the value passed for your search. You could add a set of single quote before and after the value obtained by the Request but that would be a bigger error and the source of a problem called Sql Injection.
The only way to handle this is to use a parameter query
SqlCommand command = new SqlCommand(#"SELECT KategoryID FROM Kategory
WHERE Name = #name", connection);
command.Parameters.Add("#name", SqlDbType.NVarChar).Value = Request.Params["kategory"];
Also, as noted in another answer, your code seems to not have associated the connection to the command, I think that it is just a typo here because the error message in that case would be 'need an open connection'
You forgot to assign the connection to the command. So when you call ExecuteReader(), it does not know on which connection it should be executed.
You can assign the connection like this:
SqlCommand command = new SqlCommand(
"SELECT KategoryID FROM Kategory WHERE Name = " + Request.Params["kategory"],
connection); // provide connection as second parameter!
or use connection.CreateCommand() to create your command.
Second, you forgot the quotation marks around your string:
"SELECT KategoryID FROM Kategory WHERE Name = '" + Request.Params["kategory"] + "'"
but inserting user data directly into your query opens your code to SQL Injection. Please use parameterized queries instead.
If your kategory column is not of integer data type then you need to surround your value with (') i.e single quote characters
Then your query will be like
SqlCommand command = new SqlCommand("SELECT KategoryID FROM Kategory WHERE Name ='" + Request.Params["kategory"] + "'");
The exception is caused by how you are creating your sql statement. The fix should not be correcting the syntax but using parameters instead. This will prevent sql injection attacks.
Also
You really should not be writting sql in your views, do it in your controller method instead and return the result in the Model to be used in your view. Better yet, abstract it to a different layer and call that layer from your controller. This has to do with SoS (Separation of Concerns), your code will very difficult to maintain if you just write everything into your views.
Wrap your connections, commands, and readers in using blocks.
Modified Code
#{
using(SqlConnection Praktikum2 = new SqlConnection("Data Source=Mark\\SQLEXPRESS;Initial Catalog=Connection;Integrated Security=True"))
using(SqlCommand command = new SqlCommand("SELECT KategoryID FROM Kategory WHERE Name = #name", Praktikum2))
{
command.Parameters.Add(new SqlParameter("#name", SqlDbType.VarChar){ Value = Request.Params["kategory"]});
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string ID = reader["KategorieID"].ToString() ;
Console.WriteLine("ID = {0}", ID);
}
}
}
}

Returning an integer value from SQL Server

I have an SQL query as follows:
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName=about",conn);
//cmd.Parameters.Add("#pageName","hakkinda");
SqlDataReader reader = cmd.ExecuteReader();
flID = reader.GetInt16(0);
reader.Close();
conn.Close();
I get an error message:
Invalid attempt to read when no data is present.
What's wrong?
I notice a couple potential issues:
You need to call reader.Read(), before trying to read data from it. This is usually done in a loop when people expect multiple rows.
while (reader.Read()) {
flID = reader.GetInt16(0);
}
also in your SQL if "about" is meant to be a literal and not another column name you probably need single quotes around it:
"SELECT id FROM Pages WHERE pageName='about'"
Your query is returning 0 results. This is because the parameter value in the SQL string is missing quotes. It should read as follows (notice the single quotes around the word 'about'):
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName='about'",conn);
You have to call DataReader.Read to fetch the result:
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
DataReader.Read returns a boolean, so if you have more than 1 result, you can do:
while (reader.Read()) {
// read data here
}
Your select statement should be:
"SELECT id FROM Pages WHERE pageName='about'"
If you expect only single value to be returned, you can use .ExecuteScalar()
flID = int.Parse(query.ExecuteScalar().ToString());
Also, use single quotation marks for pageName value.
SqlCommand cmd = new SqlCommand("SELECT id FROM Pages WHERE pageName='about';",conn);

Using Winforms to connect to SQL Server to easily filter data

I have a Winforms that is connecting to a SQL Server 2008 database.
I would like to be able to easily filter through data in one table.
Here is an example of what I would like:
there are 3 columns in the table, and I will have three textboxes (or any other useful control) on a form that will correspond to those three columns.
the user will be able to input a value in any one of those fields and retrieve the rest of the values pertaining to that field.
Is there already an easy solution for this?
Yes you can use DataSet or DataReader.
http://msdn.microsoft.com/en-us/library/ms171897%28v=vs.80%29.aspx
http://www.dotnetperls.com/datagridview-tutorial
I don't think there is a yet unique way of doing this. Anyways, you can simply use a SqlCommand it will allow you to execute a storedprocedure or a query as you like. The you pass the three filter values as SqlParameters.
Here is a little example:
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT * FROM MyTable Where (FieldOne == #ParameterOne Or FieldTwo = #ParameterTwo Or FieldThree = #ParameterThree)";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
// Create the command
SqlCommand command = new SqlCommand(
queryString, connection);
// Add the parameters
command.Parameters.Add(new SqlParameter("ParameterOne", txtMyTextBox1.Text));
command.Parameters.Add(new SqlParameter("ParameterTwo", txtMyTextBox2.Text));
command.Parameters.Add(new SqlParameter("ParameterThree", txtMyTextBox3.Text));
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
Then you use the SqlDataReader to get the values.

Categories

Resources