I am making a student database which contain the course id, course name, credits of each course, pass fail statement and the grades. Now I want to get the sum of the grades in a button and make them appear on a textbox. this is the code I wrote, but it's giving me an error saying the sum function doesn't exist. What should I do?
private void button1_Click(object sender, EventArgs e)
{
string ConString = " datasource = localhost; port = 3306; username = root; password = 3306";
string Query = " Select sum (grade) form studentdata.semestre1";
MySqlConnection ConDatabase = new MySqlConnection(ConString);
MySqlCommand cmdDataBase = new MySqlCommand(Query, ConDatabase);
MySqlDataReader myReader;
ConDatabase.Open();
myReader = cmdDataBase.ExecuteReader() ;
while (myReader.Read())
{
textBox2.Text = myReader.GetString(0);
}
myReader.Close();
Two reasons:
SQL query should not have space between the function and the column name
Change your query from "Form" to "FROM"
string Query = "Select SUM(grade) FROM studentdata.semestre1";
Try:
SELECT SUM(grade) FROM studentdata.semestre1
The most important change is the from.
For a more complete fix; add using, and use ExecuteScalar here:
using(MySqlConnection ConDatabase = new MySqlConnection(ConString))
using(MySqlCommand cmdDataBase = new MySqlCommand(
"SELECT SUM(grade) FROM studentdata.semestre1", ConDatabase))
{
ConDatabase.Open();
textBox2.Text = Convert.ToString(cmdDataBase.ExecuteScalar());
}
Related
Error An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code. How to fix it?
Image: http://i.stack.imgur.com/7Sibc.png
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand sc = new SqlCommand("select Title from TongHopDB", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Title", typeof(string));
dt.Load(reader);
cboxDB.ValueMember = "Title";
cboxDB.DisplayMember = "Title";
cboxDB.DataSource = dt;
conn.Close();
}
private void cboxDB_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "Select Title, Post from TongHopDB where Title = " + cboxDB.SelectedValue.ToString(); // câu query có thể khác với kiểu dữ liệu trong database của bạn
SqlConnection conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7");
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader sdr = cmd.ExecuteReader();
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
sdr.Close();
sdr.Dispose();
conn.Close();
conn.Dispose();
}
string sql = "Select Title, Post from TongHopDB where Title = '" + cboxDB.SelectedValue.ToString()+"'";
However I strongly suggest to use parameters:
string sql = "Select Title, Post from TongHopDB where Title = #Title";
cmd.Paramaters.Add( "#Title",cboxDB.SelectedValue.ToString());
I strongly suspect your Title is character typed, that's why it needs to used with single quotes as;
where Title = '" + cboxDB.SelectedValue.ToString() + "'";
But don't use this way.
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataReader objects automatically instead of calling Close or Dispose methods manually.
using(var conn = new SqlConnection(#"Data Source=QEAG1YU4664IBKF\HUYNHBAO;Initial Catalog=TonghopDB;User ID=sa;Password=koolkool7"))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "Select Title, Post from TongHopDB where Title = #title";
cmd.Parameters.Add("#title", SqlDbType.NVarChar).Value = cboxDB.SelectedValue.ToString();
// I assumed your column type is nvarchar.
conn.Open();
using(SqlDataReader sdr = cmd.ExecuteReader())
{
if(dr.Read())
{
textBox1.Text = sdr.GetValue(0).ToString();
textBox2.Text = sdr.GetValue(1).ToString();
}
}
}
cboxDB.SelectedValue is Apple according to the error shown in your screen shot. Your SQL statement is saying in plain English:
Select Title(column) and Post(column) from TongHopDB(table) where Title(column) equals Apple(column)
Apple is not a valid column!
While it would work to simply add single quotes around the value of cboxDB, you should use parameters instead of concatenating a string. http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/
I am fully new in the programming section so don't try bad help pls.
Actually I am fail focus data from phpmyadmin to c# windows form textbox1.Text area.
My database name: business, Table Name: life, columns Name : Email_id
I need to show email id 10 number row in my textbox1.Text area.
See my code
string connString = "datasource=x5x.1x1.13x.xxx;Database=business;username=sumon;password=root";
MySqlConnection connect = new MySqlConnection(connString);
MySqlCommand myCommand = connect.CreateCommand();
string input = textBox1.Text;
myCommand.CommandText = "SELECT * FROM life WHERE id = #input";
connect.Open();
MySqlDataReader reader = myCommand.ExecuteReader();
if (reader.Read())
textBox1.Text = reader["*"].ToString();
connect.Close();
you've missed to set the value for #input. I edited you code (without testing). Give it a try.
string connString = "datasource=x5x.1x1.13x.xxx;Database=business;username=sumon;password=root";
MySqlConnection connect = new MySqlConnection(connString);
MySqlCommand myCommand = connect.CreateCommand();
myCommand.Parameters.Add(new SqlParameter("input", 10));
//string input = textBox1.Text;
myCommand.CommandText = "SELECT * FROM life WHERE id = #input";
connect.Open();
MySqlDataReader reader = myCommand.ExecuteReader();
if (reader.Read())
textBox1.Text = reader["Email_id"].ToString();
connect.Close();
When I click acceptBTN I'd like to update the Quantity of a certain Item in the stockTBL
private void acceptBTN_Click(object sender, EventArgs e)
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = "UPDATE stockTBL SET Quantity = Quantity+ '" + this.quantityTxt.Text + "' where [Item Name] = '" + this.itemTxt.Text + "';";
SqlCeConnection conDataBase = new SqlCeConnection(constring);
SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
try
{
conDataBase.Open();
MessageBox.Show("Sucess");
//displays a system error message if a problem is found
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is my code, when I click the acceptBTN it just displays the MessageBox without updating the quantity.
You didn't even execute the query you just created it.Try to execute it first
conDataBase.Open();
cmdDataBase.ExecuteNonQuery();
conDataBase.Close();
Some suggestions:
Try using parameterized queries instead of string concatenation to avoid SQL Injection attacks.
Always use using statements for disposable objects in order to make sure they are properly disposed.
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = "UPDATE stockTBL SET Quantity = Quantity + #quantity where [Item Name] = #name";
using(SqlCeConnection conDataBase = new SqlCeConnection(constring))
using(SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase))
{
cmdDataBase.Parameters.AddWithValue("#quantity", int.Parse(quantityTxt.Text));
cmdDataBase.Parameters.AddWithValue("#name", itemTxt.Text);
conDataBase.Open();
cmdDataBase.ExecuteNonQuery();
cmdDataBase.Close();
}
You probably want cmdDataBase.ExecuteNonQuery. You opened the connection but never executed the query.
MSDN Referece.
Currently this code only shows the value of the "id" in database, how do i make it so it shows both "id" and "name" values in same row, like "5 - John Carpenter" ?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;password=rootpassword";
string Query = "select * from database2.employee where id='" + comboBox1.Text + "' ORDER BY Auto ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
1. use parametrised queries to avoid SQL injection attacks.
2. call Read() function on MySqlDataReader Object to read the select query results.
3. use comboBox1.SelectedItem.ToString() instead of ComboBox1.Text to get the selected Item from combobox.
Try This:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;password=rootpassword";
string Query = "select * from database2.employee where id=#id ORDER BY Auto ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
cmdDataBase.Parameters.AddWithValue("#id",comboBox1.SelectedItem.ToString());
MySqlDataReader myReader=cmdDataBase.ExecuteReader();
if(myReader.Read())
{
TextBox1.Text=myReader["id"].ToString() +" - "+myReader["name"].ToString();
}
conDataBase.Close();
}
I'm trying to make a login facility for Windows Forms Application project. I'm using Visual Studio 2010 and MS Sql Server 2008.
I referenced this article:
http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
Here is my database table named user:
I have TextBox1 for user name , TextBox2 for user password and Button1 for starting login process. Here is my code for Button1_Click method:
private void button1_Click(object sender, EventArgs e)
{
string kullaniciAdi; // user name
string sifre; // password
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
myConn.Open();
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from user where u_name='" + textBox1.Text + "';");
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
}
myConn.Close();
}
I don't have much experience with C# but i think i'm missing something small to do it right. Below i share exception message that i catched. Can you show me what i'm missing? (line 33 is myReader = myCommand.ExecuteReader();)
Considerin given answers, i updated my try block as in below but it still does not work.
try
{
SqlDataReader myReader;
string myQuery = ("select u_password from [user] where u_name=#user");
SqlCommand myCommand = new SqlCommand(myQuery, myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sifre = myReader["u_password"].ToString();
}
if (textBox2.Text.Equals(sifre))
{
Form2 admnPnl = new Form2();
admnPnl.Show();
}
}
After changing whole code as below by sine's suggestion, screenshot is also below:
And i think, somehow i cannot assign password in database to the string sifre.
code:
string sifre = "";
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.InitialCatalog = "EKS";
builder.UserID = "sa";
builder.Password = "123";
using (var conn = new SqlConnection(builder.ToString()))
{
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select u_password from [user] where u_name = #u_name";
cmd.Parameters.AddWithValue("#u_name", textBox1.Text);
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["u_password"];
if (tmp != DBNull.Value)
{
sifre = reader["u_password"].ToString();
}
}
if (textBox2.Text.Equals(sifre))
{
try
{
AdminPanel admnPnl = new AdminPanel();
admnPnl.Show();
}
catch (Exception y)
{
MessageBox.Show(y.ToString());
}
}
else
{
MessageBox.Show("incorrect password!");
}
}
}
}
User is a reserved keyword in T-SQL. You should use it with square brackets like [User].
And you should use parameterized sql instead. This kind of string concatenations are open for SQL Injection attacks.
string myQuery = "select u_password from [user] where u_name=#user";
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);
As a general recomendation, don't use reserved keywords for your identifiers and object names in your database.
Try to put user into [ ] because it is a reseved Keyword in T-SQL and use Parameters, your code is open to SQL-Injection!
private void button1_Click(object sender, EventArgs e)
{
var builder = new SqlConnectionStringBuilder();
builder.DataSource = "servername";
builder.InitialCatalog = "databasename";
builder.UserID = "username";
builder.Password = "yourpassword";
using(var conn = new SqlConnection(builder.ToString()))
{
using(var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select u_password from [user] where u_name = #u_name";
cmd.Parameters.AddWithValue("#u_name", textBox1.Text);
conn.Open();
using(var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["u_password"];
if(tmp != DBNull.Value)
{
sifre = reader["u_password"].ToString();
}
}
}
}
}
}
USER is a reserved word in T-SQL
Try putting [] around reserved words.
string myQuery = ("select u_password from [user] where u_name='" + textBox1.Text + "';");
user is a keyword.
Change it to something like
string myQuery = ("select u_password from [user] where u_name='" + textBox1.Text + "';");
Futher to that I recomend you have a look at Using Parameterized queries to prevent SQL Injection Attacks in SQL Server
User is a reserved keyword in SQL, you need to do this:
select u_password from [user] where u_name=#user
And as ever, with basic SQL questions, you should always use parameterised queries to prevent people from running any old commands on your DB via a textbox.
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myCommand.Parameters.AddWithValue("#user", textBox1.Text);