I'm working on a project. i've built a form by using visual studio express 2012 for desktop window and i'm programming in c#. here is a function that i want to use in a button event:
void connect()
{
//chaine_connexion="Data Source=MILLIONNAIRE-PC\\ITS4_2017;Initial Catalog=TP_ITS4_2017;User ID=sa;Password=***********"
string chaine = GestionEnquete.Properties.Settings.Default.chaine_connexion;
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = chaine;
cnn.Open();
// test the state of the connection
if (cnn.State == System.Data.ConnectionState.Open)
MessageBox.Show("Connexion established");
else
MessageBox.Show("Connexion not established");
//déclare an object SqlCommand type
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select count(*) from Agent" +
"where codeAgent='" + TXT_LOGIN.Text.Trim() + "'" +
"and motdepasse = '" + PW_PASSWORD.Password + "'";
//cmd.Connection = cnn;
int resultat = cmd.ExecuteNonQuery();
if (resultat > 0)
{
MessageBox.Show("the user exist in the database");
Equipe a = new Equipe();
a.Show();
Hide();
}
else
MessageBox.Show("no user");
cnn.Close();
}
when i fill the form by adding a codeAgent and a password in TXT_LOGIN and PW_PASSWORD textbox, i received these messages:
Connexion established
error: the property connection has not initialized
Now when a put cmd.Connection = cnn; just before int resultat = cmd.ExecuteNonQuery();, visual studio send the error:
Execution error: incorrect syntaxe near '='.
Please i need your help.
There's a missing space after Agent:
cmd.CommandText = "select count(*) from Agent" + ...
This leads to the SQL command select count(*) from Agentwhere... causing this syntax error.
Just add a space and it should work as expected:
cmd.CommandText = "select count(*) from Agent " +
But your code is vulnerable to SQL-Injection.
You should read about parameterized queries.
When I have my login button pressed I got this error
Error Picture
My code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection (#"C:\LOGIN\DB\LOGINDB.MDF");
string query = "Select * from Table where username='" + txtUsername.Text + "'and password='" + txtPassword.Text + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if(dtbl.Rows.Count == 1)
{
frmMain objFrmMain = new frmMain();
this.Hide();
objFrmMain.Show();
}
else
{
MessageBox.Show("Check you things");
}
}
and my sql tables:
Main table
and this
Assuming your path is correct .
Your connection strong should have data source and etc. Your format is totally wrong
Data Source=.\SQLExpress;Integrated Security=true;
AttachDbFilename=C:\MyFolder\MyDataFile.mdf;User Instance=true;
More about connection string is here
connection string guide
After you declare ur sql connection.
You need to open your connection
Sqlcon.open();
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
I face this problem when I store my data in Microsoft Azure Cloud.
here error log:
Server Error in '/' Application. 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: SQL Network Interfaces, error: 26
- Error Locating Server/Instance Specified) Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and
where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: 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: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int userId = 0;
SqlConnection con = new SqlConnection("Data Source=asimo.database.windows.net;Initial Catalog=asimo;Persist Security Info=True;User ID=veeraiyan;Password=***********");
con.Open();
SqlCommand cmd = new SqlCommand("insert into registration(username,password,email)values('" + txtusername.Text + "','" + txtpassword.Text + "','" + txtemail.Text + "')", con);
cmd.Parameters.AddWithValue("#username", txtusername.Text.Trim());
cmd.Parameters.AddWithValue("#password", txtpassword.Text.Trim());
cmd.Parameters.AddWithValue("#email", txtemail.Text.Trim());
userId = cmd.ExecuteNonQuery();
con.Close();
string message = string.Empty;
switch (userId)
{
case -1:
message = "Username already exists.\\nPlease choose a different username.";
break;
case -2:
message = "Supplied email address has already been used.";
break;
default:
message = "Registration successful.\\nUser Id: " + userId.ToString();
break;
}
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
}
The connectionstring for an Azure Sql Server database should be written as
string cnString = #"Data Source=tcp:asimo.database.windows.net,1433;
Database=asimo;Trusted_Connection=False;
User ID=veeraiyan#asimo;Password=***********;
Encrypt=True;";
Said that, your code to insert a record and to retrieve the IDENTITY column UserID is not parameterized as it should be.
The correct approach is the following
string cmdText = #"insert into registration
(username,password,email)
values(#username, #password, #email);
SELECT SCOPE_IDENTITY()";
using(SqlConnection con = new SqlConnection(cnString))
using(SqlCommand cmd = new SqlCommand(cmdText, con))
{
con.Open();
cmd.Parameters.AddWithValue("#username", txtusername.Text.Trim());
cmd.Parameters.AddWithValue("#password", txtpassword.Text.Trim());
cmd.Parameters.AddWithValue("#email", txtemail.Text.Trim());
userId = Convert.ToInt32(cmd.ExecuteScalar());
...
Notice that to retrieve the UserID you don't get the return value of ExecuteNonQuery. This method returns only the number of rows inserted by your command. Instead you could put two commands together, the first one inserts the record, the second one returns the value of the last IDENTITY generated by your connection. The method used is ExecuteScalar that returns the first column of the first row (from the last SELECT statement).
Check out https://www.google.com/search?q=agoogle&ie=&oe=#q=agoogle+c-sharp+azure+sql+connection+string for your connection string issue. Then, as suggested in comments, change:
SqlCommand cmd = new SqlCommand("insert into registration(username,password,email)values('" + txtusername.Text + "','" + txtpassword.Text + "','" + txtemail.Text + "')", con);
//change your connection string to an Azure-compatible one...
to:
SqlCommand cmd = new SqlCommand("insert into registration(username,password,email)values(#username,#password,#email, con);
and while you're at it, change:
SqlConnection con = new SqlConnection("Data Source=asimo.database.windows.net;Initial Catalog=asimo;Persist Security Info=True;User ID=veeraiyan;Password=***********");
to:
using(SqlConnection con = new SqlConnection("Data Source=asimo.database.windows.net;Initial Catalog=asimo;Persist Security Info=True;User ID=veeraiyan;Password=***********")){
//....
}
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())
{
.....
}
}