How to display numeric value selected from MS Access in the MessageBox()? - c#

Why does my code show the message
Data type mismatch in criteria expression.
My code:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string cq = "select sum(Fine) from studentbook where S_ID=" + textSID.Text + "";
command.CommandText = cq;
int a = Convert.ToInt32(command.ExecuteReader());
connection.Close();
MessageBox.Show(a.ToString());

Change code like this:
where S_ID = '" + textSID.Text + "'
Also use command.ExecuteScalar() instead of command.ExecuteReader():
int a = Convert.ToInt32(command.ExecuteScalar());
You should always use parameterized queries by the way. This kind of string concatenations are open for SQL Injection.

Related

C# : querying multiple columns into textboxes

This is my code, and I want to be able to search for a name, and then pull from the database the name, status, member_id into the textboxes in my form.
I got the name to work but how do I get the other columns and parse the output into the textboxes with the additional columns (member_id, status)? Let's say the other textboxes have the standard name such as textbox2, 3, 4...
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
string sql1 = null;
SqlDataReader dataReader;
connetionString = "Data Source=......"
sql = "SELECT NAME FROM Test_Employee WHERE Name LIKE '" + textBox1.Text.ToString() + "%'";
connection = new SqlConnection(connetionString);
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
textBox9.Text = dataReader[0].ToString();
textBox7.Text = dataReader[0].ToString();
}
connection.Close();
}
Are the fields Member_Id and Status also in the table Test_Employee? You can add them in your Select statement and get them from your SqlReader, like the code below (assuming you are using c#7 and below). You may copy and paste this code.
var connectionString = "";
var sql = #"SELECT TOP 1 Name, Member_Id, Status
FROM Test_Employee
WHERE Name LIKE #name + '%'";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("name", SqlDbType.NVarChar, 100).Value = textBox1.Text.ToString();
connection.Open();
var reader = command.ExecuteReader();
if (reader.Read())
{
textBox9.Text = dataReader["Name"].ToString();
textBox7.Text = dataReader["Name"].ToString();
textBox2.Text = dataReader["Member_Id"].ToString();
textBox3.Text = dataReader["Status"].ToString();
}
}
You will notice that instead of including the Textbox1.Text's value in your Select statement, it is added as a parameter in the SQLCommand object's Parameters. In this way your query is protected from SQL Injection. If you want to learn more, you can search c# sqlcommand parameters and why it is very important to build data access code this way.
Also, notice that I added Top 1 in your Select statement, and instead of using while, I am using if. This is because a textbox can only hold 1 result at a time in a comprehensible way. If you meant to show multiple results clearly, you need to use a different control other than a TextBox.
The using statements allow you to dispose the connection, so you don't have to call connection.Close().

How to Display data on a Label using MS Access Database in C#

I tried to get the balance and customer name to show up on the labels by getting user's input the customers ID on textbox1. But every time i tried to input the ID even just the first digit of the ID, it already shows error "Data type mismatch in criteria expression".
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
string sql = "SELECT * FROM Customer WHERE ID= '" +textBox1.Text+ "'";
cmd.CommandText = sql;
OleDbDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
labelbalance.Text = reader["Balance"].ToString();
labelname.Text = reader["Firstname"].ToString() + reader["Lastname"].ToString();
}
Remove the single quotes around Id:
string sql = "SELECT * FROM Customer WHERE ID= " + textBox1.Text;
Because you have the quotes, ID is interpreted as character.
Update
As suggested in the comment, rather use parametrized query and avoid sql injection:
string sql = "SELECT * FROM Customer WHERE ID= #var";
cmd.CommandText = sql;
cmd.Parameters.Add(new OleDbParameter("#var", int.Parse(textBox1.Text));

Get value instead of whole query

I want to get the value of the Encrypted password into a string variable. but I am getting the whole query.
Here is my code:-
string strpassword = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
Response.Write(strpassword);
In strpassword i get the whole query.
But in Toad the result is as
F52377D5FFB1A47F
how to get that in oracle?
When you write
string strpassword = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
Response.Write(strpassword);
Then you are simply displaying the string value as you are not executing the SQL which is present inside the string.
What you are looking for is the result of the SQL which is present inside the string. To get the result of the SQL stored inside the string you need to execute it.
You can try like this:
string queryString = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}",reader[0]));
}
}
finally
{
reader.Close();
}
}
As commented above, your query is prone to SQL Injection. A better way is to use paramterized query to get rid of it. Something like
string sql = "select sys.get_enc_val (#myvar) from dual";
SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("myvar", txtpassword.Text);

Whats wrong with my MS Access Update Query?

Here is my Query:
string Select = "Update DC set Password = '" + txtPass.Text + "' WHERE ID ="+Convert.ToInt32(cbxDocs.SelectedIndex + 1);
con = new OleDbConnection();
this.readconfile = new ReadConfigFile();
con.ConnectionString = this.readconfile.ConfigString(ConfigFiles.ProjectConfigFile);
con.Open();
cmd = new OleDbCommand(Select, con);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
I don't know what is wrong but it gives me an error message that "Syntax error in UPDATE STATEMENT".
I have two fields in my table 'DC' ID and Password, nothing else.
PASSWORD is reserve word enclose it in square brackets like [Password], so your query should start like:
"Update DC set [Password]....
Consider using parameterized query, this will save you from Sql Injection
I think u don't need the ' on ur query and Password is reserved in almost every ddb.
And you could use parameters to avoid the concat with the +
Ex.
string pass = TxtPass.Text;
int s = cbxDocs.SelectedIndex+1;
string Select = "Update DC set Password = #a WHERE ID = #o";
OleDbCommand cmd = new OleDbCommand(Select, conn);
cmd.Paramaters.AddWithValue("#a", pass);
cmd.Parameters.AddWithValue("#o", s);
//everything else....

assign the variable with MySql

I want to assign my variable [vPrenom_id_obtenu] by the value that I get in my MySql DB ...
With the following code, I receive an error message :
does not contain a definition for 'ExecuteScalar' ....
string vFistNam_id_get;
string connDataBaseStr = "server=myserver;user=####;database=myDataBase;port=3306;password=dsdfsdfsdf123;";
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy WHERE column_famillyname='" + vFamillyName + "'";
MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr);
connDataBase.Open();
vFistNam_id_get = (string)connDataBase.ExecuteScalar();
connDataBase.Close();
How can I retrieve the value that is in "column_fistname_id"?
The type of two columns of my table
Le type de deux colonnes de ma table [column_fistname_id] and [column_famillyname] is «text'.
ExecuteScalar is a method to call on an instance of a MySqlCommand not of a MySqlConnection
The right way to go is:
using(MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr))
{
connDataBase.Open();
MySqlCommand cmd = new MySqlCommand(sqlDataBaseSelect, connDataBase);
vFistNam_id_get = (string)cmd.ExecuteScalar();
}
However your code is wrong for another reason.
this sql string
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy " +
"WHERE column_famillyname='" + vFamillyName + "'";
leads the way to SqlInjection
You should rewrite it in this way
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy " +
"WHERE column_famillyname=?family";
and then before calling ExecuteScalar add a Parameter to the command
cmd.Parameters.AddWithValue("?family", vFamillyName);
And as added value you don't have to worry about datatype delimiter (single quote in this case)
You need to use MySqlCommand to use ExecuteScalar. You're also missing the SQL in your source code, i.e. select * from something, or a stored proc name.
public static int GetNumRows(String OrchardName)
{
// Create Connection
MySqlConnection con = new MySqlConnection(_connectionString);
// Create Command
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT COUNT(*) FROM orchards WHERE OrchardName = #OrchardName";
cmd.Parameters.Add("#OrchardName", OrchardName);
// Return Count
con.Open();
Int32 NumRows = (Int32)cmd.ExecuteScalar();
return NumRows;
}
Example:
MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr);
connDataBase.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT column_fistname_id FROM table_identy WHERE column_famillyname='" + vFamillyName + "'";
MySqlDataReader reader = command.ExecuteReader();
string vFistNam_id_get = null;
while (reader.Read())
{
vFistNam_id_get = (int)reader["column_fistname_id"];
}
You're using the ADO.NET types wrong. The easiest thing to do would be to use the MySqlHelper static methods, like this:
string vFistNam_id_get = (string)
MySqlHelper.ExecuteScalar(dbConnString, "select `col1` from `table1`");

Categories