MYSQL Connector not connecting - c#

I have this code atm in c# and the MYSQL connection wont work:
int chk;
MySqlConnection con = new MySqlConnection(#"Data Source=sql9.freemysqlhosting.net;port=3306;Initial Catalog=new;UserId=sql9FFFFF9;password=X3FFFFYX8;");
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from sql9164489.users where username='" + txt_user.Text + "' and password='" + txt_pass.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
chk = Convert.ToInt32(dt.Rows.Count.ToString());
//If Correct
if (chk == 1)
{
MessageBox.Show("Connected");
}
else
{
MessageBox.Show("Incorrect");
}
con.Close();

con.Opern() raises an error:
Authentication to host 'sql9.freemysqlhosting.net' for user 'sql9FFFFF9' using method 'mysql_native_password' failed with message: Access denied for user 'sql9FFFFF9'#'188.244.39.23' (using password: YES)
I guess it's pretty clear

Download MySQL connector for .net and your working will be more easy as database will display in server explorer and then you can copy and paste the connection string from there.
Here is link

Related

SQL exception was unhandled by user code on connection open

i am beginner to microsoft asp.net and i got An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code error when trying to select value from Microsoft visual studio database. The error was on the con.Open() line
Below is my code:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\Ng\Documents\Visual Studio 2015\Projects\Assignment6\Assignment6\App_Data\photoCompetition.mdf;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework");
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM User WHERE email=#username and password=#word", con);
cmd.Parameters.AddWithValue("#username", emailtext.Text);
cmd.Parameters.AddWithValue("#word", passwordtext.Text);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
con.Close();
if (dt.Rows.Count > 0)
{
Response.Redirect("Default.aspx");
}
else
{
lblMsg.Text = "Your username and word is incorrect";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
So your first issue is that you had a space in your Sql Connection string.
C: \Users\Ng\Documents\Visual Studio 2015\Projects\Assignment6\Assignment6\App_Data\photoCompetit‌​ion.mdf
Now since your query looks valid and assuming the tables and columns exists, you are having a problem with the SQL query you are trying to execute. I see two options here.
Enclose your parameters with a single quote to denote it as a string
SqlCommand cmd = new SqlCommand("SELECT * FROM User WHERE email='#username' and password='#word'", con);
Use SqlParameterCollection.Add Method (String, SqlDbType, Int32).
cmd.Parameters.Add("#username", SqlDbType.Text).Value = emailtext.Text;
cmd.Parameters.Add("#word", SqlDbType.Text).Value = passwordtext.Text;
Also, don't forget to close your SqlConnection with con.Close();

Database System.Data.SqlClient.SqlException

I'm trying to use database:
SqlConnection sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\DB\LogiDB.mdf;Integrated Security=True;Connect Timeout=30");
string query = "Select * from tbl_Login Where username = '" + textBox1.Text.Trim().ToLower() + "' and password = '" + textBox1.Text.Trim().ToLower() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{
//
}
my files is:
dbo.Table.sql
LogiDB.mdf
LogiDB_log.ldf
tbl_Login.sql
not sure what I'm doing wrong but when I press to button I got this with line sda.Fill(dtbl);:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid object name 'tbl_Login'.
As the error says: Invalid object name 'tbl_Login'
This might mean:
tbl_Login table doesn't exist in you database
you are connecting to wrong database
Since you have tbl_Login.sql script, I guess it contains table definition. Therefore you would need to run script to create table in your LogiDB database.
Here there is example how to connect to local database
Here is my code work perfectly,
You can try this and compare your code
SqlConnection cn = new SqlConnection("Data Source=AVREST\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
cn.Open();
SqlCommand cmd = new SqlCommand("select loginID,loginPassword from logintavle where loginID='" + textBox1.Text + "'and loginPassword='" + textBox2.Text + "'", cn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//sda.SelectCommand = cmd;
DataTable dataset = new DataTable();
sda.Fill(dataset);
if (dataset.Rows.Count > 0)

Store a timer value in a database? c#

I have a global variable which is set up for the timer, "I", the program I'm creating has a user play a game level and store their level time in a database with other users. This is what I have already.
public static class Global
{
public static int I = 0;
}
^ this is the global variable for the timer.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Adam\Documents\Data2.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sad = new SqlDataAdapter("Select Count(*) From Login where Username= '" + txtUsername.Text + "' and Password='" + txtPassword.Text + "'", con);
SqlCommand cmd = new SqlCommand("INSERT INTO HighScore (Username, Score) VALUES(#Username,#Score)", con);
DataTable dt = new DataTable(); //empty table
sad.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
con.Open();
cmd.Parameters.AddWithValue("#USERNAME", txtUsername.Text);
cmd.Parameters.AddWithValue("#Score", Global.I);
}
else // else it will display this error
{
MessageBox.Show("Please enter the correct login details");
}
^^ this is the code for the end screen of the game, as you can see i've tried taking the Global.I and addwithvalue #Score which is in the HighScore table in my database.
Now when i click the button it doesn't write anything to the database but I don't get any errors when i try and save, this is why i'm confused.
Any help would be appreciated, Thanks.
before executing any command you first must open the connection. You are opening the connection after calling Fill()!!. You will also have to execute cmd. Try:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Adam\Documents\Data2.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter sad = new SqlDataAdapter("Select Count(*) From Login where Username= '" + txtUsername.Text + "' and Password='" + txtPassword.Text + "'", con);
SqlCommand cmd = new SqlCommand("INSERT INTO HighScore (Username, Score) VALUES(#Username,#Score)", con);
con.Open();
cmd.Parameters.AddWithValue("#USERNAME", txtUsername.Text);
cmd.Parameters.AddWithValue("#Score", Global.I);
DataTable dt = new DataTable(); //empty table
sad.Fill(dt);
cmd.ExecuteNonQuery();
It is also admirable that you know how to correctly use parameters, however you use them only in 1 case instead of both queries.

syntax error in from clause C# and Access

I keep getting this run time error, syntax error in from clause. I tried already using my sql query in access and it seems ok.
Here's my code and I am using C# windows form with text box and button
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Misry27\Documents\Visual Studio 2010\Projects\Inventory\Inventory\bin\Debug\Inventory.mdb");
OleDbCommand cmd = new OleDbCommand("select * from Employee where username = '" + this.tbUsername.Text + "' and password = '" + this.tbPassword.Text + "';", conn);
OleDbDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
int count = 0;
while (dr.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username or Password is correct");
}
else
{
MessageBox.Show("Username or Password Incorrect");
}
conn.Close();
As explained in the comments above, PASSWORD is a reserved keyword and need to be enclosed in square brackets when used in query executed from net.
The usual advice follows. Use parameterized query to avoid parsing problem and sql injections, use the using statement around your disposable objects.
using(OleDbConnection conn = new OleDbConnection(a correct connection string here))
using(OleDbCommand cmd = new OleDbCommand(#"select * from Employee
where username = ? AND [Password] = ?", conn);
{
conn.Open();
cmd.Parameters.AddWithValue("#p1", this.tbUsername.Text);
cmd.Parameters.AddWithValue("#p2", this.tbPassword.Text);
using(OleDbDataReader dr = cmd.ExecuteReader())
{
.....
}
}

Getting error SqlException was unhandled by user code

I'm creating a Registration form for new user sign up. Im getting the following error. I searched for solution on google, but none of them helped me.
Error : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).
Could you please help me out with this?
Code :
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from regform where username='" + TextBox1.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Label1.Text = "User Name is Already Exist";
}
else
{
Label1.Text = "UserName is Available";
}
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
con.Open();
String str = "Insert into regform values ( '" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "')";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
Session["name"] = TextBox1.Text;
Response.Redirect("Default.aspx");
con.Close();
}
}
Your connection string seems off
Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;
Using the AttachDbFilename=... element indicates you're using SQL Server Express, but the Express default installation would be using the SQLEXPRESS instance name - so your connection string should be
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;
Have you tried with this connection string? Any luck?
If that doesn't work - can you make sure what edition of SQL Server you have installed? Connecting to it in Management Studio - what do you use as server name?? And if you're connected - what does SELECT ##Version return?
utilize this example taken from Retrieving Data Using a DataReader
you will see quickly where you are making the slight code mistake
static void HasRows(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
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();
}
}
change your code here
SqlCommand cmd = new SqlCommand("Select * from regform where username='" + TextBox1.Text + "'", con);
Either create a Property or even better a Stored Procedure
The exception suggests that your connection string is wrong.
Isn't Initial Catalog=InstanceDB missing from your connection string? Where InstanceDB is the name of your database.
Use command parameters! If you don't, you will face several issues:
You will be threatened by SQL injection attacks!
You will have to deal with the special handling of null entries.
You will have to escape quotes in strings.
You will have to use the right formatting for date values.
Lengthy string concatenations look ugly.
SqlCommand cmd = new SqlCommand(
"SELECT * FROM regform WHERE username = #usr", con);
cmd.AddWithValue("#usr", TextBox1.Text);
Do the same for the insert statement.

Categories

Resources