"ExecuteNonQuery: Connection property has not been initialized." - c#

Here is the code:
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/charlyn_dale/Documents/Visual Studio 2010/Projects/LMS/WindowsFormsApplication2/Accounts.accdb;Persist Security Info=False");
OleDbCommand conn = new OleDbCommand(str);
con.Open();
string query = "insert into Account ([Username],[Password],FirstName,MiddleName,LastName,Age,Section,Gender,Address,AccountStatus) values('" + txt1.Text + "','" + txt2.Text + "','" + txt4.Text + "','" + txt5.Text + "','" + txt6.Text + "','" + txt7.Text + "','" + txt8.Text + "','" + cmb2.Text + "','" + txt9.Text + "','" + cmb1.Text + "')";
OleDbCommand cmd = new OleDbCommand(query, con);
conn.ExecuteNonQuery();
MessageBox.Show("Registration Success!");
con.Close();
and the error is:
Connection property has not been initialized

There are 3 main issues in your Access DB connection:
OleDbConnection connection string property has not initialized when opening OLE DB connection (note that con is different from conn in this context).
The connection string wrongly assigned to variable conn which declared as OleDbCommand, use OleDbConnection instead.
The connection string data source path seems invalid by using slash sign for directory separator (assuming target file exists in Windows folder), use backslash escape sequence (\\) or single backslash with literal string instead (e.g. #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\......").
Hence, the correct connection sequence should be like this:
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\charlyn_dale\\Documents\\Visual Studio 2010\\Projects\\LMS\\WindowsFormsApplication2\\Accounts.accdb;Persist Security Info=False");
using (OleDbConnection conn = new OleDbConnection(str))
{
conn.Open();
// security tips: better use parameter names to prevent SQL injection on queries
// and put value checking method for all textbox values (sanitize input)
string query = "insert into Account ([Username],[Password],FirstName,MiddleName,LastName,Age,Section,Gender,Address,AccountStatus) values ('" + txt1.Text + "','" + txt2.Text + "','" + txt4.Text + "','" + txt5.Text + "','" + txt6.Text + "','" + txt7.Text + "','" + txt8.Text + "','" + cmb2.Text + "','" + txt9.Text + "','" + cmb1.Text + "')";
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
conn.ExecuteNonQuery();
}
... // other stuff
conn.Close();
}
NB: using statements added due to OLE DB connection should be disposed immediately after usage to free up resources.
Similar issues:
get an error as ExecuteNonQuery:Connection property has not been initialized
ExecuteNonQuery: Connection property has not been initialized (access database)
ExecuteNonQuery: Connection property has not been initialized

Related

Error in insert query in visual studio

I'm new in this field. Trying to insert the values from textbox to my database table, but I get an error at
adapter.InsertCommand.ExecuteNonQuery();
Can anyone help me solve this?
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql,con);
adapter.InsertCommand = new SqlCommand(sql,con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();
Since your table is called table and that is a SQL reserved word, you have two choices:
Change your table name. This is the only option you should be considering but for completeness;
Quote the name of the table:
insert into [table] values....
You do not list your column name on insert. This means you are also attempting to insert your identity column as well. Always list your column names
insert into NewName (firstname, lastname, username, email, password, contact)
values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')
Yes I've done it .I was using "user" in table column which is not allowed .After changing the column name everything works.
This is the code
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql, con);
adapter.InsertCommand = new SqlCommand(sql, con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();

using windows form c# to add values to Mysql database

I need to get the userid(primary key auto_increment) from another table(login) into userdetails table. When trying to run it I keep getting this error " incorrect integer value: 'LAST_INSERT_ID()' for column 'userid' at row 1".
I've tried to take LAST_INSERT_ID() out and run another query after query4 to insert the value into the userid but I can't get it to insert into the right row it just opens a new row.
this is the code am trying to run.
try
{
//This is my connection string i have assigned the database file address path
string MyConnection2 = "datasource=localhost;port=3310;database=e-votingsystem;username=root;password=Password12;";
//this is my insert query in which i am taking input from the user through windows forms
string Query2 = "INSERT INTO vote (username) VALUE ('" + usernameInputBox.Text + "');";
string Query3 = "INSERT INTO login (username,upassword) VALUE ('" + usernameInputBox.Text + "','" + passwordInputBox.Text + "');";
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUES ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text+"');";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query2, MyConn2);
MySqlCommand MyCommand3 = new MySqlCommand(Query3, MyConn2);
MySqlCommand MyCommand4 = new MySqlCommand(Query4, MyConn2);
MySqlDataReader MyReader2;
MySqlDataReader MyReader3;
MySqlDataReader MyReader4;
// opens new connection to database then executes command
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader(); // Here the query will be executed and data saved into the database.
while (MyReader2.Read())
{
}
MyConn2.Close();
// opens new connection to database then executes command
MyConn2.Open();
MyReader3 = MyCommand3.ExecuteReader();
while (MyReader3.Read())
{
}
MyConn2.Close();
//opens new connection to database the exexcutes command
MyConn2.Open();
MyReader4 = MyCommand4.ExecuteReader();
while (MyReader4.Read())
{
}
MyConn2.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
MessageBox.Show("Hello " + forename + surname, "read and accept the terms and conditions to continue");
//new termsAndConditionsPage().Show();
//Hide();
}
As explained in other answer, you have the LAST_INSERT_ID between single quotes and this transform it in a literal string not in a statement to execute. However also removing the quotes I am not sure that you can retrieve the LAST_INSERT_ID using a connection different from the one that originates the AUTOINCREMENT number on the login table. In any case you should use a different approach and, as a first thing, you should remove ASAP the string concatenations and use parameters (Reason: Sql Injection or SurName = O'Neill)
string Query2 = "INSERT INTO vote (username) VALUE (#uname)";
string Query3 = #"INSERT INTO login (username,upassword) VALUE (#uname, #upass);
SELECT LAST_INSERT_ID();";
string Query4 = #"INSERT INTO userdetails
(nationalinsurance,userid,forename,middlename,
surname,housenumber,street,towncity,postcode,suffix)
VALUES (#insurance, #userid, #forename, #middlename,
#surname, #housenum, #street, #town, #postcode, #suffix)";
Now open just one connection and build three commands, all between an using statement
using(MySqlConnection con = new MySqlConnection(.....constring here....))
using(MySqlCommand cmd2 = new MySqlCommand(Query2, con))
using(MySqlCommand cmd3 = new MySqlCommand(Query3, con))
using(MySqlCommand cmd4 = new MySqlCommand(Query4, con))
{
con.Open();
// Add the parameter to the first command
cmd2.Parameters.Add("#uname", MySqlDbType.VarChar).Value = usernameInputBox.Text;
// run the first command
cmd2.ExecuteNonQuery();
// Add parameters to the second command
cmd3.Parameters.Add("#uname", MySqlDbType.VarChar).Value = usernameInputBox.Text;
cmd3.Parameters.Add("#upass", MySqlDbType.VarChar).Value = passwordInputBox.Text;
// Run the second command, but this one
// contains two statement, the first inserts, the
// second returns the LAST_INSERT_ID on that table, we need to
// catch that single return
int userID = (int)cmd3.ExecuteScalar();
// Run the third command
// but first prepare the parameters
cmd4.Parameters.Add("#insurance", MySqlDbType.VarChar).Value = nationalInsuranceInputBox.Text;
cmd4.Parameters.Add("#userid", MySqlDbType.Int32).Value = userID;
.... and so on for all other parameters
.... using the appropriate MySqlDbType for the column type
cmd4.ExecuteNonQuery();
}
you current query has an error
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "','"+"LAST_INSERT_ID()"+"','" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');SELECT LAST_INSERT_ID();"
try the attached query
In your text query string you have: "','"+"LAST_INSERT_ID()"+"','". Note that the "','"s before and after the "LAST_INSERT_ID()" are incorrectly enclosing the LAST_INSERT_ID() term in single quotes.
Try the following query:
string Query4 = "INSERT INTO userdetails (nationalinsurance,userid,forename,middlename,surname,housenumber,street,towncity,postcode,suffix) VALUE ('" + nationalInsuranceInputBox.Text + "',"+"LAST_INSERT_ID()"+",'" + forenameInputBox.Text + "','" + middleNameInputBox.Text + "','" + surnameInputBox.Text + "','" + houseNumberInputBox.Text + "','" + streetTextBox.Text + "','" + towncityTextBox.Text + "','" + postcodeInputBox.Text + "','" + suffixComboBox.Text + "');";

Save,Update and delete page. Saving duplicated data

I was watching https://www.youtube.com/watch?v=SJ-RyDl5E7U It basically teaches me how to create my update and delete button after following the video my program works just like his!
But there is no "checking" statement for my btnSave, allowing the user to enter duplicated data in the data base if they click more than once shown here
So I was wondering if there is a "checking statement" I can use, like if the IndexNumber (first column) exist there will be a message box showing out saying something like "ID is already exists"
This is my current code for the btnSave
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text + "','" + numGPA.Value + "')", con);
cmd.ExecuteNonQuery();
con.Close();
As you are using ado.net something like this;
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + "Application.StartupPath" + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
//get a count records with your index number
SqlCommand validate = new SqlCommand(string.Format("SELECT count(IndexNumber) FROM GlennTeoStudents WHERE IndexNumber = {0}", numIN.Value), con);
int count = (Int32)validate.ExecuteScalar();
if (count == 0)
{
//insert your unqiue index number into a new row
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text + "','" + numGPA.Value + "')", con);
cmd.ExecuteNonQuery();
}
else
{
//don't insert it, do something else like return an error
}
con.Close();
You should add an existence check:
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value +
"','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text +
"','" + numGPA.Value + "') WHERE NOT EXISTS ( SELECT * FROM
GlennTeoStudents WHERE IndexNumber = '" + numIN.Value + "')", con);

ExecuteNonQuery results in "Connection property has not been initialized." [duplicate]

This question already has answers here:
ExecuteNonQuery: Connection property has not been initialized.
(7 answers)
Closed 9 years ago.
I am using VS2010 and SQL Server 2008 Management Studio
protected void btnsave_click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("Data Source=SAAD-CH-HP;Initial Catalog=ovms;Integrated Security=True;");
myConnection.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO request(reqtype, source,employeeID, vehID, destination) VALUES ('"
+ official + "','" + source + "','" + emp_id + "','" + DropDownList1 + "','" + destination + "')");
cmd.ExecuteNonQuery();
myConnection.Close();
}
As I run the program this exception occurs
ExecuteNonQuery: Connection property has not been initialized.
You have not associated the command with the connection.
You need to add another parameter to your SqlCommand constructor, with the connection handle.
Please update you code to this below. Set the SQLCommand's connection property.
protected void btnsave_click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("Data Source=SAAD-CH-HP;Initial Catalog=ovms;Integrated Security=True;");
myConnection.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO request(reqtype, source,employeeID, vehID, destination) VALUES ('" + official + "','" + source + "','" + emp_id + "'," + DropDownList1.Text + ",'" + destination + "')");
cmd.Connection = myConnection;
cmd.ExecuteNonQuery();
myConnection.Close();
}
or in the construction after you SQL Test, add myConnection
SqlCommand cmd = new SqlCommand(#"INSERT INTO request(reqtype, source,employeeID, vehID, destination) VALUES ('" + official + "','" + source + "','" + emp_id + "'," + DropDownList1.Text + ",'" + destination + "')",myConnection);

Getting SSL Provider Error when using IntegratedSecurity

SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = "Data Source=.;Database = deptStore;Integrated Security = true;";
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into Employee values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "','" + TextBox12.Text + "','" + TextBox13.Text + "')";
cmd.Connection = cnn;
cmd.ExecuteNonQuery();
Response.Write("Record Save");
cnn.Close();
But I am getting following Error:
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = "Data Source=.;Database = deptStore;Integrated Security = true;";
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into Employee values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "','" + TextBox12.Text + "','" + TextBox13.Text + "')";
cmd.Connection = cnn;
cmd.ExecuteNonQuery();
Response.Write("Record Save");
cnn.Close();
But iam getting following Error:
SqlException was unhandled by user code
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)
Kindly help me to understand the error and rectify it.
Make sure you have enabled TCP/IP in SQL Server Configuration Manager: Enable Network Access in SQL Server Configuration Manager
Also, Start the SQL Server Browser Service: Start and Stop the SQL Server Browser Service

Categories