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);
Related
This question already has answers here:
how to get the last record number after inserting record to database in access
(6 answers)
Closed 1 year ago.
Am working with Access as Database in C# (Visual Studio 15). I want to save form entries (add record) into the Access Database and would want the corresponding ID of the record to show in MsgBox upon a successful saving. I have tried the following:
private void Form21_Load(object sender, EventArgs e)
{
try
{
connection.Open();
checkConnection.Text = "Server Connection, Successful";
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error, Server not connected " + ex);
}
}
private void Button6_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into Students_File ([YourNames],[Nationality],[StateOfOrigin],[PlaceOfBirth],[DoB],[HomeAddress],[LastSchools1],[LastClass1],[LastSchools2],[LastClass2],[LastSchools3],[LastClass3],[AdmClass],[CurrentClass],[Guidian],[GuardianContact],[UserName],[PassWord],[Gender],[RegistrationDate]) values('" + YourNames.Text + "','" + Nationality.Text + "','" + StateOfOrigin.Text + "','" + PlaceOfBirth.Text + "','" + DoB.Text + "','" + HomeAddress.Text + "','" + LastSchools1.Text + "','" + LastClass1.Text + "','" + LastSchools2.Text + "','" + LastClass2.Text + "','" + LastSchools3.Text + "','" + LastClass3.Text + "','" + AdmClass.Text + "','" + CurrentClass.Text + "','" + Guidian.Text + "','" + GuardianContact.Text + "','" + UserName.Text + "','" + PassWord.Text + "','" + Gender.Text + "','" + RegistrationDate.Text + "')";
command.ExecuteNonQuery();
//MessageBox.Show("Congrats! Your registration, is successful. You may now click close button, then proceed to login");
command.CommandText = "Select * from Students_File where UserName='" + UserName.Text + "' and PassWord='" + PassWord.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Congrats! Your registration, is successful. You may now click close button, then proceed to login");
this.Close();
}
else if (count > 1)
{
MessageBox.Show("Sorry, the chosen username or password is currently existing or picked by another user. Consequently, your registration was not successful. Do please, decide another but a unique one. Thank you");
}
connection.Close();
}
You can do it this way:
using (OleDbCommand Command = new OleDbCommand("", conn))
{
Command.CommandText = "Your big ugly mess - need to change this to parmaters!)";
Command.Connection.Open();
Command.ExecuteNonQuery();
Command.CommandText = "Select ##Identity";
var intLastID = Command.ExecuteScalar;
MsgBox("Last id into database = " + intLastID);
}
As noted, you do want to change that insert command - it too long, too difficult to maintain, and subject to mistakes in code and even sql injection.
But, for now, you can use the above approach to get/pick up the last ID insert.
In solution to my inquiry, i have the following code (From Kevin):
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("#CategoryName", OleDbType.Integer);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
Now, my challenge is how do i get the ID to appear in messagebox after a successful record creation. Please consider my earliest code in this post in connection with this.
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
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);
Scenario:
I want to input data from textbox into the database based on microsoft data base (.mdb)
I already searching and find good clue and my result was here.
This Code below was inside command button click event:
using (OdbcConnection conn= new OdbcConnection())
{
conn.ConnectionString = #"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=C:\\BlaBlaBla.mdb;Uid=Admin;Pwd=;";
conn.Open();
using (OdbcCommand cmd = new OdbcCommand(
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
And when I click the command button, I get unfriendly exception
ERROR [42S02] [Microsoft][ODBC Microsoft Access Driver] Could not find
output table 'TABLENAME'.
That happened when I insert cmd.ExecuteNonQuery. If I didn't insert that, of course nothing happens in my table target.
So what mistakes did I make in that code? What should I do?
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", myConnection))
change this into
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", Conn))
you define Conn as your connection string not "myConnection"
So i changed to OleDbConnection And My Problem Cleared,
using (OleDbConnectionconn= new OleDbConnection())
{
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\LOSERONE\Documents\DATABASE\Latihan1.mdb";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand (
"INSERT INTO TABLENAME (FIELD1,FIELD2,FIELD3) VALUES ('" + txtFIELD1Input.Text + "','" + txtFIELD2Input.Text + "','" + txtFIELDInput.Text + "' )", conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
Seems, to connected the database must same as the connection string in the properties on the targeted database.
Does anyone can tell me what is the difference OleDbConnection with OdbcConnection in .mdb database file?!
This problem is because sql connection's default database after login is not the same where your table 'TABLENAME' exists. Try to add database name before table like this:
INSERT INTO DBNAME..TABLENAME (FIELD1, FIELD2)
replace your myConnection to Conn
Am not able to fix the error below:
`"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 'When,Then) values( '79','WBT-CoE','gyj','yi','yi')' at line 1"` error.
Here's the code:
protected void Button3_Click(object sender, EventArgs e){
string MyconnectionString = "server=localhost;database=requirement_doc;Uid=t;Pwd=123;";
MySqlConnection conn = new MySqlConnection(MyconnectionString);
MySqlCommand cmd;
DataTable dt1 = new DataTable();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT Req_ID, Actor FROM UseCase where Req_ID='" + txtReqID.Text + "' AND Actor='" + DropDownList1.Text + "'";
MySqlDataAdapter da1 = new MySqlDataAdapter();
da1.SelectCommand = cmd;
da1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
Label1.Text = "Data already exist";
}
else
{
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,When,Then) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
}
try
{
cmd.ExecuteNonQuery();
Label1.Text = " Successfully saved";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
Surround When and then with `` because they are reserved names.
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,`When`,`Then`) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
When and Then are reserved names in MySQL. So if you use those as column names, you get that error.