MySQL connection to phpMyAdmin created database with C# - c#

As our question got closed yesterday, we unfortunately have to open a new one. So here goes.
This is the old question: MySQL connection with C# through PHPMyAdmin created database
Firstly, thanks for all the answers! So we have implemented Rahul and ActiveHigh's answers and updated the code. Furthermore, we have added a way to check if the connection is a success or not. Now when we try to insert data we get the error message from the catch. The test location is still the same. Here is an image of the table in the database: https://www.dropbox.com/s/g2c70ty9qb1h7bw/ScreenshotDatabase.png
Anyone have any idea what is going wrong or an idea how to debug it?
(We have checked inside phpmyadmin whether or not the table is empty with a SQL query. It is empty.
protected void Button1_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection connection;
string server = "db.cce-solutions.dk";
string database = "web626445";
string uid = "******";
string password = "******";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
try
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
DisplayMessage.Text = "Data entered succesfully.";
MySqlCommand cmd = new MySqlCommand("insert into Booking (yourName,YourEmail,YourPhone,Category,Date,Description) values(#Name,#Email,#Telephone,#Category,#Date,#Description)", connection);
cmd.Parameters.AddWithValue("#Name", YourName.Text);
cmd.Parameters.AddWithValue("#Email", YourEmail.Text);
cmd.Parameters.AddWithValue("#Telephone", YourPhone.Text);
cmd.Parameters.AddWithValue("#Category", Category.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Date", "test");
cmd.Parameters.AddWithValue("#Description", Description.Text);
cmd.ExecuteNonQuery();
}
else
{
DisplayMessage.Text = "Database connection failed.";
}
}
catch (Exception ex)
{
DisplayMessage.Text = "Error occured. Please try again later.";
}
connection.Close();

We found out we had assigned erroneous column names. In the insert statement we wrote yourName, yourEmail and so on (as you can see below) which needed to be changed to Name, Email, and so on.
MySqlCommand cmd = new MySqlCommand("insert into Booking (yourName,YourEmail,YourPhone,Category,Date,Description) values(#Name,#Email,#Telephone,#Category,#Date,#Description)", connection);
Furthermore we removed the if loop since we did not need it and added a throw to the catch to get more detailed feedback. Hope this can help anyone stuck in the same problem.
Don't be us - check your column names! ;)

Related

C# Databases SQLite Locked Database Error

I am currently writing a code using C# and SQLite. There is an error being throwing stating that the database is locked twice in a message box.
The query works on SQLite DB Browser however, when it is placed in C# code it throws the error.
Here is the code that is giving me an error:
cmd.CommandText = "UPDATE customers SET Bill = Bill - "+textBox2.Text+" WHERE customers.CustomerID = " + textBox1.Text + ";";
There seems to be an issue with the equals sign, might be something wrong with the arithmetic process.
Complete code:
SQLiteConnection myconn = new SQLiteConnection(#"Data Source = C:\Users\chick\Newspaper.db");
SQLiteCommand cmd = myconn.CreateCommand();
cmd.CommandText = "UPDATE customers SET Bill = (Bill - "+textBox2.Text+") WHERE customers.CustomerID = " + textBox1.Text + ";";
myconn.Open();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Succesfully Update");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
UPDATE:
Changed format to using() {} however it is still not working. Program is crashing
New Code:
using (SQLiteConnection myconn = new SQLiteConnection(#"Data Source = C:\Users\chick\Newspaper.db"))
{
var sql = "Update customers SET Bill = Bill - #pay WHERE customers.CustomerID = #cid;";
myconn.Open();
using (var cmd = new SQLiteCommand(sql, myconn))
{
cmd.Parameters.AddWithValue("#cid", textBox1.Text);
cmd.Parameters.AddWithValue("#pay", textBox2.Text);
cmd.ExecuteNonQuery();
}
}
The problem is that some other part of the program (or some other program) still has an active transaction.
You must properly clean up all commands that access the database, i.e., use using everywhere.
Thank you to all that have answered. We realized the issue was that we never closed the reader in previous code.

C# MySQL Syntax error in SQL Statement

I have this simple method that is supposed to insert a row into a DB. It is throwing an exception.
private void AddToLiveQueue(int user_id, bool release = false)
{
string sql = "INSERT INTO live_support_queues (user_id, release, created_at, updated_at)";
sql += " VALUES(?user_id, ?release, ?created_at, ?created_at)";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?user_id", user_id);
cmd.Parameters.AddWithValue("?release", release);
cmd.Parameters.AddWithValue("?created_at", DateTime.UtcNow);
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
SendEmail email = new SendEmail();
email.Send(ex.Message + " " + ex.ToString());
}
}
I am getting this error:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'release, created_at, updated_at) VALUES(70, 0, '2017-09-22 23:00:16.686741', '20' at line 1"
Any help is greatly appreciated. Thanks!
release is a reserved word, and needs escaped with ` symbols if used as an identifier.
https://dev.mysql.com/doc/refman/5.7/en/keywords.html

C# ASP.NET Code doesn't insert data into my database, but doesn't throw any errors either

I am working on a project for a class. One of the requirements is that my program pulls information from a few textboxes on a web form and stores the values into a database. I have pulled information out of a database and figured putting stuff into one would be roughly the same process. When I tried however I get no errors, but when I open the database up there is nothing there either.
Code:
OleDbConnection con;
OleDbCommand com;
con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + #"C:\Users\D40010490\Desktop\GMDatabase.accdb");
com = con.CreateCommand();
try
{
con.Open();
lblError.Text = "Successfully Connected to Database";
String firstName = txtFirstName.Text;
String lastName = txtLastName.Text;
String email = txtEmail.Text;
String password = txtPassword.Text;
String cpassword = txtCPassword.Text;
String Description = txtDesc.Text;
com.CommandText = "INSERT INTO Users "
+ "(lastname, firstname, email, password) "
+ "VALUES (" + "'" +lastName+"'"
+ "'" + firstName +"'"+ "'"+email+"'"+ "'"+password+"');";
con.Close();
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
}
please advise.
You never actually execute the command:
com.CommandText = "INSERT INTO Users "...
com.ExecuteNonQuery();
con.Close();
You should also get in the habit of using parameters instead of concatenating SQL (especially when dealing with users and passwords).
You need to call com.ExecuteNonQuery() in order to run the command.
Mark Cidade have reason , always you want insert in database you should execute the retrieve, check very good your code and bug if is necesary for resolve...

getting exception in creating a password change form

i am creating password change form. when i execute the form and fill the textboxes it give an exception with the message There is already and open DataReader associated with this command which must be closed first.
he is the code which i am using:
private bool CompareStrings(string string1, string string2)
{
return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "data source=.;Initial catalog=inventory;Integrated Security=true";
con1.Open();
SqlCommand cmd = new SqlCommand("SELECT ISNULL(username, '') AS username, ISNULL(password,'') AS password FROM login WHERE username='" + textBox1.Text + "' and password='" + textBox2.Text + "'", con1);
SqlDataReader dr = cmd.ExecuteReader();
string userText = textBox1.Text;
string passText = textBox2.Text;
while (dr.Read())
{
if (this.CompareStrings(dr["username"].ToString(), userText) &&
this.CompareStrings(dr["password"].ToString(), passText))
{
SqlCommand cmd2 = new SqlCommand("UPDATE login SET password='" + textBox3.Text + "'where username='" + textBox1.Text + "'", con1);
cmd2.ExecuteNonQuery();
MessageBox.Show("Password Changed Successfully");
}
else
{
MessageBox.Show("Incorrect Old password");
}
}
dr.Close();
con1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
You cannot execute a command while a SqlDataReader is open on the same connection. You can do either of the two following things to change your code:
Create a second connection and run the update query on that second connection.
Store the data from the reader, close the reader and later update all data. In your case, you could store all usernames to update and update them in one update query using Username in (<yourlisthere>)
When you open a DataReader the connection serves only the requests coming from the DataReader. The SqlCommand used to Update the login table cannot run.
Unless you add this to your connectionstring
MultipleActiveResultSets = True;
Here you can find the reference to MARS
And here the words from MSDN about the DataReader
While the SqlDataReader is being used, the associated SqlConnection is
busy serving the SqlDataReader, and no other operations can be
performed on the SqlConnection other than closing it. This is the case
until the Close method of the SqlDataReader is called. For example,
you cannot retrieve output parameters until after you call Close.
As a side note, but very important. Do not use string concatenation to build sql commands. Use always a parameterized query
string cmdText = "UPDATE login SET password=#pwd where username=#usr";
using(SqlCommand cmd2 = new SqlCommand(cmdText, con1))
{
cmd2.Parameters.AddWithValue("#pwd", textBox3.Text);
cmd2.Parameters.AddWithValue("#usr", textBox1.Text);
cmd2.ExecuteNonQuery();
}
A parameterized query will avoid Sql Injection problems and let you simplify your command text.
This is true also for the SELECT query at the beginning of your code. Do not trust the input coming from your user
Another problem that you should be aware of is the storing of clear text passwords in your database. This is considered a very bad practice from a security point of view. You should apply an hash function to you password and store the result. While checking for the correct password you repeat the hash function on the user input and check the result against the hashed password stored in database

Insert Data from form to Access database

I have a problem when i m doing a connection to access then error is occured Could not find file 'C:\Users\Geeta\Desktop\test1.mdb'. and mycode is :
protected void btn_submit_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = (#"Provider=Microsoft.Jet.OLEDB.4.0;Data source= C:\Users\Geeta\Desktop\test1.mdb");
conn.Open();
string query = "insert into test (First Name,Address,Email,Password) values ('" + txt_fstname.Text + "','" + txt_email.Text + "', '"+txt_pass.Text+"', '"+txt_add.Text+"')";
OleDbCommand cmd = new OleDbCommand(query,conn);
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("Default.aspx");
}
plz help me.
"Thanks"
Try to use the following connection string:
conn.ConnectionString = (#"Provider=Microsoft.Jet.OLEDB.4.0;Data source=C:\Users\Geeta\Desktop\test1.mdb;");
Remark:
There is no blank between = and the database
The database path must end with a ;
Additionally:
It seems that you try to access the database using ASP.NET. Please keep in mind, that the user that runs the website has not necessarily the permission to edit the database.

Categories

Resources