error: the property connection has not initialized - c#

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.

Related

MySql Update won't work

Good day! I need help please..
This is my code on c# whenever I execute it nothing happens no error or hint
string myConnection = " datasource=localhost;port=3306;username=root;password=wolf";
string Query = " UPDATE bikerentaldb.tblbikes SET status='Rented',renteddate=NOW(),assignedreturndate='" + txtToBeReturned.Text + "' WHERE bikeID='" + txtBikeIdRent.Text + "'";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(Query, myConn);
myConn.Open();
MessageBox.Show("Data Saved");
myConn.Close();
I am not sure why the Upate won't work but when I execute this code on MySql
UPDATE bikerentaldb.tblbikes SET status='Rented',renteddate=NOW(),assignedreturndate=NOW() WHERE bikeID='2';
It works just fine can someone help me?
A command should be executed to do anything. Your code misses the call to SelectCommand.ExecuteNonQuery() line after the open connection. However after fixing this trivial error you could encounter other problems with the values concatenated to form your command text. What if the user types an invalid date? Have you ever heard of Sql Injection hacks?
This is how your code should be written after adding validation to your inputs and parameters to send values to your database
int bikeID = 0;
if(!Int32.TryParse(txtBikeIdRent.Text, out bikeID)
{
MessageBox.Show("Invalid number");
return;
}
DateTime returnDate;
if(!DateTime.TryParse(txtToBeReturned.Text , out returnDate)
{
MessageBox.Show("Invalid date");
return;
}
string myConnection = ".....";
string Query = #"UPDATE bikerentaldb.tblbikes
SET status='Rented', renteddate=NOW(),
assignedreturndate=#date
WHERE bikeID=#id";
using(MySqlConnection myConn = new MySqlConnection(myConnection))
using(MySqlCommand cmd = new MySqlCommand(Query, myConn))
{
myConn.Open();
cmd.Parameters.Add("#date", MySqlDbType.Date).Value = returnDate;
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = bikeID;
int rowUpdated = cmd.ExecuteNonQuery();
if(rowUpdated > 0)
MessageBox.Show("Record updated");
else
MessageBox.Show("No record match");
}

Update ExceptionNonQuery

I am trying to update an MS Access table and it keeps throwing an error:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in string in query expression 'EmID = '234'.
The EmID is in the database. Please help
public partial class Sales : Form
{
...
private void btnUpdate_Click(object sender, EventArgs e)
{
int EmpID = int.Parse(txtEmpID.Text);
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\SalesData.mdb");
OleDbCommand update = new OleDbCommand("UPDATE Sales SET Printer = '" + txtPrinter.Text + "', Ink = '" +txtInk.Text + "', Paper = '"+txtPaper.Text+"' WHERE EmID = '" + txtEmpID.Text + " ", con);
con.Open();
update.ExecuteNonQuery();
con.Close();
MessageBox.Show("Sales Updated");
}
...
}
You have forgotten to add a closing quote after the WHERE value. But fixing the problem adding the missing quote serves only to hide other problems.
What if one of your textboxes contains a single quote? You will get again a syntax error exception caused by the string concatenation where the quotes serve as delimiter of your values. With a single quote typed by your user you will confuse the Sql Parser again.
To fix this problem (and a more serious one called Sql Injection) you need to start using parameters
string cmdText = #"UPDATE Sales SET Printer = #printer,
Ink = #Ink, Paper = #Paper
WHERE EmID = #id";
using(OleDbConnection con = new OleDbConnection(...))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.Add("#printer", OleDbType.VarWChar).Value = txtPrinter.Text;
cmd.Parameters.Add("#ink", OleDbType.VarWChar).Value = txtInk.Text;
cmd.Parameters.Add("#paper", OleDbType.VarWChar).Value = txtPaper.Text;
cmd.Parameters.Add("#id", OleDbType.VarWChar).Value = txtEmpID.Text;
cmd.ExecuteNonQuery();
}

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.

Trouble with query, execute non scalar not behaving as I thought

I'm having trouble with a SQL query:
using (SqlConnection conn = new SqlConnection("user id=user;" + "password=pass;" + "server=server;" + "database=db;"))
{
using (SqlCommand comm = new SqlCommand(#"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'"))
{
conn.Open();
comm.Connection = conn;
MessageBox.Show("TEST: {0}", Convert.ToString((int)comm.ExecuteScalar()));
}
}
I'm expecting to get an int in the message box conveying the number of rows that BolagsID occurs in. But I get 0 every time. I've tried the query in SQL Server Management Studio and it works fine there. What am I doing wrong/missing?
EDIT:
This works, but now I don't know how to parameterize the values:
string query = #"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = " + BolagsID;
ADODB.Connection conn2 = new ADODB.Connection();
ADODB.Recordset rs = new ADODB.Recordset();
string strConn = "Provider=...;Data Source=...;Database=...;User Id=...;Password=...";
conn2.Open(strConn);
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic;
rs.Open(query, conn2);
if (rs.Fields[0].Value > 0)
...stuff...
Like others are saying, parameters are a good idea. Here's something to get you started:
string query = #"SELECT Count(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = #BolagsID";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#BolagsID", SqlDbType.NVarChar).Value = BolagsID;
conn.Open();
MessageBox.Show("TEST: {0}", Convert.ToString((int)cmd.ExecuteScalar()));
conn.Close();
}
Basically a 0 is returned if there is an error in your query, so even though SSMS is smart enough to resolve it, the sql command isn't.
A quick way to make sure that everything else is working okay is to change the query to just "SELECT Count(*) FROM [CompaniesDB].[dbo].[Companies]". If that doesn't work then the issue could lie with your database connection (permissions?) or something else.
Try assigning SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'" to a string str as follows
string str =#"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'";
using (SqlConnection conn = new SqlConnection("user id=user;" + "password=pass;" + "server=server;" + "database=db;"))
{
using (SqlCommand comm = new SqlCommand(str))
{
conn.Open();
comm.Connection = conn;
MessageBox.Show("TEST: {0}", Convert.ToString((int)comm.ExecuteScalar()));
}
}
Then do a watch/quickwatch on str's value to get the exact query that is getting run and then run the same query in Sql Managment studio. If you get 0 in Sql Management Studio as well, then the problem is that the data is just not there.
I tried a lot of stuff before trying out a whole different approach. This gives me the result I want:
string query = #"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = " + BolagsID;
ADODB.Connection conn2 = new ADODB.Connection();
ADODB.Recordset rs = new ADODB.Recordset();
string strConn = "Provider=...;Data Source=...;Database=...;User Id=...;Password=...";
conn2.Open(strConn);
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic;
rs.Open(query, conn2);
if (rs.Fields[0].Value > 0)
...stuff...
Note that both connection and record set are closed outside of this code snippet.

Categories

Resources