Search Data From Mysql and Set it into Textbox c# - c#

I'm trying to make a program that searches data from MySQL database and displays the values in the text box using Text Change event.
So far here is my code:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string sqlstring = "database = db_phonebook; user = root; password = ''; server = 'localhost'; SSL Mode = None";
MySqlConnection mysqlcon = new MySqlConnection(sqlstring);
MySqlCommand mysqlcom;
MySqlDataReader mdr;
mysqlcon.Open();
string selectquery = "SELECT * FROM 'tbl_phonebook' WHERE CID =" + cid.Text;
mysqlcom = new MySqlCommand(selectquery, mysqlcon);
mdr = mysqlcom.ExecuteReader();
if (mdr.Read())
{
name.Text = mdr.GetString("Name");
address.Text = mdr.GetString("Address");
contact.Text = mdr.GetString("Contact_Number");
email.Text = mdr.GetString("Email_Address");
}
else
{
MessageBox.Show("Record Not Found!");
}
mysqlcon.Close();
}
But the error says MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''tbl_phonebook' WHERE CID =' at line 1'
any idea how do I fix this?

I'm sorry to say there is a LOT that is wrong here, some of it much more important even than the bug you know about. Try this instead, and learn from the patterns shown:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string constring = "database = db_phonebook; user = root; password = ''; server = 'localhost'; SSL Mode = None";
//backticks instead of single quotes around the table/object name
string sql = "SELECT * FROM `tbl_phonebook` WHERE CID = #CID";
//using blocks make sure the connection is closed and disposed,
// EVEN IF AN EXCEPTION IS THROWN
// Original code would have left the connection hanging open.
using (var con = new MySqlConnection(constring))
using(var cmd = new MySqlCommand(sql, con))
{
//parameterized query instead of string concatenation.
// THIS IS A **HUGE** DEAL!!
// It's important enough you should STOP and go FIX
// any code you have anywhere that already uses concatenation.
cmd.Parameters.AddWithValue("#CID", cid.Text);
con.Open();
using (var mdr = cmd.ExecuteReader())
{
if (mdr.Read())
{
name.Text = mdr.GetString("Name");
address.Text = mdr.GetString("Address");
contact.Text = mdr.GetString("Contact_Number");
email.Text = mdr.GetString("Email_Address");
}
else
{
//Do NOT show an interrupting textbox that steals focus from
// an actively typing user based on a textchanged event!
name.Text = "";
address.Text = "";
contact.Text = "";
email.Text = "";
}
}
}
}

Related

C# SQL Web Application - My Web App will not perform necessary update/deletes when method is called

I am literally stumped. I've spent two days working at this. I have tried scrolling through the internet but nothing I seem to try worked like try/catch blocks, using etc.
So here goes..
I have a Web Application asp c# , which is connected to an sql database that I have written within Visual Studio 'Database.mdf' .
The Database contains a number of Football Players and their details, I want to be able to update and delete these details however my sql commands are not coming into affect (I am new to this so it's probably something ridiculously simple to most of you but nonetheless)
I have a number of buttons in which I use to both sort the data on screen in order. They work fine, I just use a static variable string for that. However the methods I have written for the SQL Commands are not working for me. The methods are called also on Button_Click but in the case of Update/Delete nothing changes, it's as if the sql query never updated the database
Please if you have any idea how I can fix this let me know. My head's fried.
Here are a few of the methods including display data :
protected void Page_Load(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\David\\Desktop\\WebApplication5\\WebApplication5\\App_Data\\Database2.mdf\";Integrated Security=True";
cn = new SqlConnection(str);
cn.Open();
mycount();
displayData();
// updateData();
// deleteData();
}
protected void mycount()
{ // count no of els in table
max = 0;
var cmd = cn.CreateCommand();
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
while (reader.Read()) max++;
reader.Close();
}
protected void displayData()
{
var cmd = cn.CreateCommand();
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
for (int i = 0; i < count; i++) reader.Read();
TextBox1.Text = "" + reader[0];
TextBox2.Text = "" + reader[1];
TextBox5.Text = "" + reader[2];
TextBox6.Text = "" + reader[3];
TextBox7.Text = "" + reader[4];
TextBox8.Text = "" + reader[5];
reader.Close();
}
protected void updateData()
{
var cmd = cn.CreateCommand();
string query = "UPDATE [Footballer] SET [Appearances] = #appear , [NumberOfGoals] = #goals Where [PlayerName] = #name ";
cmd.CommandText = query;
int appear = int.Parse(TextBox6.Text);
int goals = int.Parse(TextBox8.Text);
string name = TextBox1.Text;
cmd.Parameters.AddWithValue("#Player_ID", name);
cmd.Parameters.AddWithValue("#app", appear);
cmd.Parameters.AddWithValue("#goals", goals);
cmd.ExecuteNonQuery();
}
protected void deleteData()
{
string searchName = TextBox4.Text;
TextBox1.Text = "Deleted";
TextBox2.Text = "Deleted";
TextBox5.Text = "Deleted";
TextBox6.Text = "Deleted";
TextBox7.Text = "Deleted";
TextBox8.Text = "Deleted";
var cmd = cn.CreateCommand();
string query = "Delete from [Footballer] where [PlayerName] = #PlayerName_ID";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#PlayerName_ID", searchName);
cmd.ExecuteNonQuery();
}
Here is a screen of what I got visually if it helps:
Gui View
Most probably because you do not commit the transaction. There is an example here https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqltransaction.commit

Wrong output being displayed on the window even when the console is showing the matching values from the database

I have attached a screenshot of my output screen .My code is giving me an unusual flaw.It is a Login program that I am working on.And the problem is that when I debug & run the code entering the correct inputs to the specified fields exactly similar to the entries in the database. The console is properly fetching the right values but the output I get is an unsuccessful Login.I do not understand why is this happening could someone guide me!
`
private void button1_Click(object sender, EventArgs e)
{
String s1 = textBox1.Text;
String s2 = textBox2.Text;
SqlConnection cnn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
String sql = ("select Userid,Password from reg where Userid='" + s1 + "' and Password='" + s2 + "' ");
cnn.Open();
String userid="";
String password="";
SqlCommand cmd = new SqlCommand(sql,cnn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while(reader.Read())
{
userid = reader.GetString(0);
password = reader.GetString(1);
Console.WriteLine(userid);
Console.WriteLine(password);
}
The If statement checks if the entered userid & password are similar to the existing userid passwrd in the DB.
if((s1.Equals(userid)) && (s2.Equals(password)))
{
MessageBox.Show("LOGIN SUCCESSFULLY DONE>>");
}
else
{
MessageBox.Show("LOGIN UNSUCCESSFUL ....");
}
}
May be there are additional spaces into strings? Try using Trim()
String s1 = textBox1.Text.Trim();
String s2 = textBox2.Text.Trim();
and
userid = reader.GetString(0).Trim();
password = reader.GetString(1).Trim();
Do you known that just one record is returned from database?

Incorrect syntax near '(' when updating record in database

My code is producing an Incorrect syntax near '(' exception. I have tried two different ways but they both produce the same exception. I am trying to update a record in the database.
Here is my code and the line that produces the exception is the Execute non query line. The updater.Fill(dtable) which is commented out also produces the same exception.
protected void btnSave_Click(object sender, EventArgs e)
{
int found = 0; // No match found so far
// Get the current selected Manufacturer
string currentManufacturer = grdManufact.SelectedRow.Cells[1].Text;
string currentIsModerated = grdManufact.SelectedRow.Cells[3].Text;
// Connect to the database
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
SqlConnection conn = new SqlConnection(strConnectionString);
conn.Open();
// Try to find if new record would be a duplicate of an existing database record
if (txtManufactureName.Text != currentManufacturer)
{
string findrecord = "SELECT * From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "'";
SqlDataAdapter adpt = new SqlDataAdapter(findrecord, conn);
DataTable dt = new DataTable();
found = adpt.Fill(dt);
}
if (found == 0) // New record is not a duplicate you can proceed with record update
{
String query;
if (checkBoxModerated.Checked)
{
query = "UPDATE VehicleManufacturer (ManufacturerName, ManufacturerDescription, Ismoderated) Values ('" + txtManufactureName.Text + "','" + txtDescription.Text + "','true') WHERE ManufacturerName = " + currentManufacturer + ";";
}
else
{
query = "UPDATE VehicleManufacturer (ManufacturerName, ManufacturerDescription, Ismoderated) Values ('" + txtManufactureName.Text + "','" + txtDescription.Text + "','false') WHERE ManufacturerName = " + currentManufacturer + ";";
}
using (SqlCommand command = new SqlCommand(query, conn))
{
command.ExecuteNonQuery();
}
//using (SqlDataAdapter updater = new SqlDataAdapter(command))
// {
// DataTable dtable = new DataTable();
// updater.Fill(dtable);
// }
txtMessage.Text = "Manufacturer record changed Successfully";
txtManufactureName.Text = "";
txtDescription.Text = "";
checkBoxModerated.Checked = false;
}
else
{ // Record is a duplicate of existing database records. Give error message.
txtMessage.Text = "Sorry, that manufacturer name already exists.";
}
}
You are using the incorrect syntax for UPDATE statements.
Instead of
UPDATE Table (Fields) VALUES (Values) WHERE ...
It should be
UPDATE Table SET Field1=Value1, Field2=Value2 WHERE ...
Additionally, you have a SQL injection vulnerability (although this is not the reason for your exception).
Do not use string concatenation for SQL queries with user input. Use prepared statements instead.
Try this approach , it's safer also:
var isModerated = checkBoxModerated.Checked ; //true or false
//var isModerated = (checkBoxModerated.Checked)? 'true' : 'false' ;
command.Text = "UPDATE VehicleManufacturer
SET ManufacturerName = #manufacturerName,
ManufacturerDescription = #manufacturerDescription,
IsModerated = #isModerated
WHERE ManufacturerName = #manufacturer_name";
command.Parameters.AddWithValue("#manufacturerName", txtManufactureName.Text);
command.Parameters.AddWithValue("#manufacturerDescription", txtDescription.Text);
command.Parameters.AddWithValue("#isModerated", isModerated);
command.Parameters.AddWithValue("#manufacturer_name", txtManufactureName.Text);
command.ExecuteNonQuery();

How to Access Specific Fields of Data from Database

I am working on a inventory software in which I want to access the ProductName and Product Price by Comparing it With the ProductCode, the Data I've Already Stored in Database table named ProductLog, the Data in Product Log is:
ItemNO Productode ProductName ProductPrice
1 123 lux 58
2 321 soap 68
now I want that I only enter productCode in my textbook named txtProductCode, and press tab then ProductPrice(txtProductPrice) and ProductName(txtProductName) boxes fills automatically.
The code I tried to compare the Productcode and access values is:
private void txtProdcutCode_Leave(object sender, EventArgs e)
{
///////////////////////////////////////////////////////////////////////
InitializeComponent();
string sql;
int productCode = 0;
productCode = Convert.ToInt32(txtProdcutCode.Text);
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, dbo.ProductLog.ProductName";
sql = " WHERE ProductLog.ProductCode = " + txtProdcutCode.Text + "";
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
while (sdr.Read())
{
txtProductPrice.Text = sdr["ProductPrice"].ToString();
txtProductName.Text = sdr["ProductName"].ToString();
}
//lblTotalQuestion.Text = intQNo.ToString();
sdr.Close();
rs = null;
cn.Close();
/////////////////////////////////////////////////////////////////////////
}
but in line productCode = Convert.ToInt32(txtProdcutCode.Text); it says Input string was not in a correct format.
Please help me out with this problem.
EDIT:
I've also tried this code :
private void txtProdcutCode_Leave(object sender, EventArgs e)
{
///////////////////////////////////////////////////////////////////////
string sql;
// int productCode = 0;
//productCode = Convert.ToInt32(txtProdcutCode.Text);
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, AND dbo.ProductLog.ProductName";
sql = " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
while (sdr.Read())
{
txtProductPrice.Text = sdr["ProductPrice"].ToString();
txtProductName.Text = sdr["ProductName"].ToString();
}
//lblTotalQuestion.Text = intQNo.ToString();
sdr.Close();
rs = null;
cn.Close();
/////////////////////////////////////////////////////////////////////////
}
but it says Incorrect syntax near the keyword 'WHERE'. means I am making mistake in calling database table in my query, but I am not able to find out the mistake ...
There are some issues with your SQL.
You were originally overwriting the sql variable and only ended up with a WHERE clause;
You don't have a FROM statement so the database doesn't know where you're trying to retrieve records from.
The use of AND in a SELECT statement is incorrect; you just need commas to separate the fields.
You're never selecting ProductPrice from the DB, but selecting ProductName twice!
You're not using parameterized SQL for your query, leaving your app open to SQL injection attacks.
To address this (points 1-4, I will leave point 5 for your own research),
sql = "";
sql = "SELECT dbo.ProductLog.ProductName, AND dbo.ProductLog.ProductName";
sql = " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
Should be
sql += "SELECT ProductName, ProductPrice";
sql += " FROM dbo.ProductLog";
sql += " WHERE ProductCode = '" + txtProdcutCode.Text + "'";
Note: This answer assumes that the value of txtProductCode.Text is an integer!
EDIT: It turns out that the column, ProductCode, was a VarChar. For OP
and others reading this question, when you get SQL conversion errors
check your column datatype in SQL server and make sure it matches what
you're submitting.
That's the basics. There are many other improvements that can be made but this will get you going. Brush up on basic SQL syntax, and once you get that down, look into making this query use a parameter instead of directly placing txtProductCode.Text into your query. Good luck!
Never call InitializeComponent method twice.It's creating your form and controls and it's calling in your form's constructor.Probably when you leave your textBox it's creating again and textBox will be blank.therefore you getting that error.Delete InitializeComponent from your code and try again.
Update: your command text is wrong.here you should use +=
sql += " WHERE dbo.ProductLog.ProductCode = " + txtProdcutCode.Text + "";
But this is not elegant and safe.Instead use paramatirezed queries like this:
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT dbo.ProductLog.ProductName,dbo.ProductLog.ProductName WHERE dbo.ProductLog.ProductCode = #pCode";
cmd.Parameters.AddWithValue("#pCode", txtProdcutCode.Text );

Getting Data From Sql Server 2008 with C#

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);

Categories