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

I have searched this forum, and have tried a multitude of possible solutions I found, but nothing is working. can anyone shed some light on this situation? Thanks!
SqlConnection con = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(
"INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID) " +
"VALUES ('" + GenName.Text + "' , '" + GenAdd.Text + "' , '" + GenCity.Text + "' , '" + GenState.Text + "' , '" + GenZip.Text + "' , '" + GenPhone.Text + "' ," +
" '" + GenContact.Text + "' , '" + GenEPAID.Text + "' ), con");
cmd.ExecuteNonQuery();
con.Close();

It looks like when you are creating your SqlCommand, you have the connection as part of the Insert statement. Specifically, ", con" is still wrapped inside your text string. If you move your last double quote to after the parenthesis, it should work.
However, I would suggest rewriting your code like this:
using (var con = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True"))
{
if(ConnectionState.Closed == con.State) con.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = $#"INSERT INTO tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)
VALUES ('{GenName.Text}', '{GenAdd.Text}', '{GenCity.Text}', '{GenState.Text}', '{GenZip.Text}', '{GenPhone.Text}', '{GenContact.Text}', '{GenEPAID.Text}')";
cmd.ExecuteNonQuery();
}
}

This is the code that I ended up using. Thanks everyone for your help.
SqlConnection myConnection =
new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
SqlCommand myCommand = new SqlCommand(
"INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)" +
"VALUES (#GenName, #GenAdd, #GenCity, #GenState, #GenZip, #GenPhone, #GenContact, #GenEPAID)");
myCommand.Parameters.AddWithValue("#GenName", GenName.Text);
myCommand.Parameters.AddWithValue("#GenAdd", GenAdd.Text);
myCommand.Parameters.AddWithValue("#GenCity", GenCity.Text);
myCommand.Parameters.AddWithValue("#GenState", GenState.Text);
myCommand.Parameters.AddWithValue("#GenZip", GenZip.Text);
myCommand.Parameters.AddWithValue("#GenPhone", GenPhone.Text);
myCommand.Parameters.AddWithValue("#GenContact", GenContact.Text);
myCommand.Parameters.AddWithValue("#GenEPAID", GenEPAID.Text);
myConnection.Open();
myCommand.Connection = myConnection;
MessageBox.Show("You Have Successfully Added a New Generator To SQL");
myCommand.ExecuteNonQuery();
myConnection.Close();

Related

How to back up SQL Server database via Winforms C#

I'm stuck on a issue where I need to backup my database via Winforms. I managed to find a sample SQL code in order to achieve this task.
My query here :
SqlConnection CON = new SqlConnection("Data Source=DBS\\DB;Initial Catalog=" + metroTextBox1.Text + ";Integrated Security=True");
Sql = "BACKUP DATABASE " + metroComboBox1.Text + " TO DISK = '" + metroTextBox4.Text + "\\" + metroComboBox1.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";
I have no idea how to proceed next. What should I use in this scenario? (ExecuteScalar, ExecuteNonQuery..etc)
Any help would be appreciated.
Note that Date time is also there in back up file name.
You define the SQL command to execute, and then instantiate a SqlCommand. Since the SQL statement isn't expected to return any data (a result set etc.), use ExecuteNonQuery:
string Sql = "BACKUP DATABASE " + metroComboBox1.Text + " TO DISK = '" + metroTextBox4.Text + "\\" + metroComboBox1.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";
using(SqlConnection CON = new SqlConnection("Data Source=DBS\\DB;Initial Catalog=" + metroTextBox1.Text + ";Integrated Security=True"))
using(SqlCommand cmdBackup = new SqlCommand(Sql, CON))
{
// open connection, execute command, close connection
CON.Open();
cmdBackup.ExecuteNonQuery();
CON.Close();
}
The general code:
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (var comm = conn.CreateCommand())
{
comm.CommandType = CommandType.Text;
comm.CommandText = "BACKUP DATABASE...";
comm.ExecuteNonQuery();
}
}

How to create connection between MySQL table to query in C#

I wrote the query for inserting data to MySQL table "Persons":
SqlConnection con = new SqlConnection();
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}
But it's not working. I have one connection for the whole database, but it's not working for a specific table. How I can create a connection between specific table to query in C#?
What is it? SqlConnection con = new SqlConnection() you need to pass a connection string which comprises DBname, username, pasword, server name ... etc; you are not passing those information anywhere then how can you expect it to connect to your database without having the information.
Pass the connection string either in constructor or using the property.
SqlConnection con = new SqlConnection(connection_string)
(OR)
SqlConnection con = new SqlConnection();
con.ConnectionString = connection_string;
There are different ways to insert data into the tables. I suggest to use parametrized sql query to keep safe from malicious occurrence.
Firstly you should have a ConnectionString something like this:
string connectionString = "Persist Security Info=False;User ID=UserName;Password=YourPassword;Server=ServerName";
And than:
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO TableName (Col1, Col2, ColN) VALUES (#Col1, #Col2, #ColN)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Col1", txtName.Text);
cmd.Parameters.AddWithValue("#Col2", txtPhone.Text);
cmd.Parameters.AddWithValue("#ColN", txtAddress.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
Try this code. Please edit your credentials before trying.
Replace localhost with SQL server instance name, user id with your MySQL server instance user id, password with your MySQL server instance password and testdb with your database name. It should work fine.
string connectionString = #"server=localhost;user id=admin;password=admin;database=testdb;";
SqlConnection con = new SqlConnection(connectionString);
try
{
String insert = "INSERT INTO Persons (id,Name,Surname,Address,Phone) VALUES ('" + txtId.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + txtAddress.Text + "','" + txtPhone.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(insert,con);
cmd.ExecuteNonQuery();
con.Close();
}
catch
{
MessageBox.Show("Id is not valid");
}

Update error if data does not exist

I managed to create my own "save, update, delete" program with SQL after watching a video.
I have an issue, if I click "update" without having the "IndexNumber" in the database, nothing will happen.
Can anybody advise me on how to improve my "update" button? Perhaps if the data does not exist, the program can prompt the user with a message box instead of doing nothing. Like "IndexNumber does not exist therefore unable to update"
My update code
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(#"UPDATE GlennTeoStudents SET IndexNumber = '" +
numIN.Value + "',Name = '" + txtName.Text + "',Age ='" + txtAge.Text +
"',HandPhoneNumber = '" + txtHP.Text + "',GPA = '" + numGPA.Value +
"' WHERE (IndexNumber='" + numIN.Value + "')", con);
cmd.ExecuteNonQuery();
con.Close();
SqlCommand.ExecuteNonQuery() returns the number of rows affected (int).
You could check on the return value:
SqlCommand.ExecuteNonQuery(asd)
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
if (!(rowsAffected > 0))
{
throw new ArgumentException(<Your Message>);
}
Then just catch the exception wherever you call the method and display your messagebox with
MessageBox.Show(<Your Message>)
try
{
.....
con.Open();
SqlCommand cmd = new SqlCommand(#"Select count(*) from GlennTeoStudents
WHERE (IndexNumber='" + numIN.Value + "')", con);
int count1 = cmd.ExecuteScalar();
if (count1 != 0)
{
do your update
}
else
{
give your message box
}
}

Incorrect Syntax near ' '.C#

I get error
INCORRECT SYNTAX NEAR ' '
Here is my code:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection=conn;
cmd.CommandText = "update student set Name='" + textBox1.Text + "',Family='" + textBox2.Text + "',Fathername='" + textBox3.Text + "',ShenasName='" + textBox4.Text + "',CodeMeli'" + textBox5.Text + "',Tavalod'" + maskedTextBox1.Text + "',Address'" + richTextBox1.Text + "',Madraak'" + textBox7.Text + "',Shahriye'" + textBox8.Text + "',Mobile'" + textBox6.Text + "'where Name=" + textBox1.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
My database is SQL Server Express.
There are some errors:
missing equals after: CodeMeli=, Tavalod=, Address=, Madraak=, Shahriye=, Mobile=
missing ending of the sql statement + "'"
This will work:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = "update student set Name='" + textBox1.Text + "',Family='" + textBox2.Text + "',Fathername='" + textBox3.Text + "',ShenasName='" + textBox4.Text + "',CodeMeli='" + textBox5.Text + "',Tavalod='" + maskedTextBox1.Text + "',Address='" + richTextBox1.Text + "',Madraak='" + textBox7.Text + "',Shahriye='" + textBox8.Text + "',Mobile='" + textBox6.Text + "'where Name='" + textBox1.Text + "'";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
In any case, I recommend you the use of Parameters. Why?
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd= new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = #"UPDATE Student SET Name=#Name, Family=#Family, Fathername=#Fathername, ShenasName=#ShenasName, CodeMeli = #CodeMeli,Tavalod=#Tavalod, Address=#Address, Madraak=#Madraak, Shahriye=#Madraak, Mobile=#Mobile WHERE Name=#Name";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Family", textBox2.Text);
cmd.Parameters.AddWithValue("#Fathername", textBox3.Text);
cmd.Parameters.AddWithValue("#ShenasName", textBox4.Text);
cmd.Parameters.AddWithValue("#CodeMeli", textBox5.Text);
cmd.Parameters.AddWithValue("#Tavalod", maskedTextBox1.Text);
cmd.Parameters.AddWithValue("#Address", richTextBox1.Text);
cmd.Parameters.AddWithValue("#Madraak", textBox7.Text);
cmd.Parameters.AddWithValue("#Shahriye", textBox8.Text);
cmd.Parameters.AddWithValue("#Mobile", textBox6.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
using table2 instead of student
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = "update table2 set Name='" + textBox1.Text + "',Family='" + textBox2.Text + "',Fathername='" + textBox3.Text + "',ShenasName='" + textBox4.Text + "',CodeMeli='" + textBox5.Text + "',Tavalod='" + maskedTextBox1.Text + "',Address='" + richTextBox1.Text + "',Madraak='" + textBox7.Text + "',Shahriye='" + textBox8.Text + "',Mobile='" + textBox6.Text + "'where Name='" + textBox1.Text + "'";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
OR
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlCommand cmd= new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection = conn;
cmd.CommandText = #"UPDATE table2 SET Name=#Name, Family=#Family, Fathername=#Fathername, ShenasName=#ShenasName, CodeMeli = #CodeMeli,Tavalod=#Tavalod, Address=#Address, Madraak=#Madraak, Shahriye=#Madraak, Mobile=#Mobile WHERE Name=#Name";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Family", textBox2.Text);
cmd.Parameters.AddWithValue("#Fathername", textBox3.Text);
cmd.Parameters.AddWithValue("#ShenasName", textBox4.Text);
cmd.Parameters.AddWithValue("#CodeMeli", textBox5.Text);
cmd.Parameters.AddWithValue("#Tavalod", maskedTextBox1.Text);
cmd.Parameters.AddWithValue("#Address", richTextBox1.Text);
cmd.Parameters.AddWithValue("#Madraak", textBox7.Text);
cmd.Parameters.AddWithValue("#Shahriye", textBox8.Text);
cmd.Parameters.AddWithValue("#Mobile", textBox6.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Clear();
cmd.Connection=conn;
cmd.CommandText = #"
UPDATE
Student
SET
Name=#Name, Family=#Family, Fathername=#Fathername, ShenasName=#ShenasName, CodeMeli = #CodeMeli,
Tavalod=#Tavalod, Address=#Address, Madraak=#Madraak, Shahriye=#Madraak, Mobile=#Mobile
WHERE
Name=#Name";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Family", textBox2.Text);
cmd.Parameters.AddWithValue("#Fathername", textBox3.Text);
cmd.Parameters.AddWithValue("#ShenasName", textBox4.Text);
cmd.Parameters.AddWithValue("#CodeMeli", textBox5.Text);
cmd.Parameters.AddWithValue("#Tavalod", maskedTextBox1.Text);
cmd.Parameters.AddWithValue("#Address", richTextBox1.Text);
cmd.Parameters.AddWithValue("#Madraak", textBox7.Text);
cmd.Parameters.AddWithValue("#Shahriye", textBox8.Text);
cmd.Parameters.AddWithValue("#Mobile", textBox6.Text);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("jj");
Here is the code. First Format your query properly, your query was unreadable. Second use Command parameters to avoid SQL Injection. You can read in Wikipedia about sql injection. Third write "nice" textBox ID, which have some meaning.
Look at your CommandText. There are some Parameters without ( = )
Format like this :
cmd.CommandText = "update student set Name='" + textBox1.Text + "',
Family='" + textBox2.Text + "',
Fathername='" + textBox3.Text + "',
ShenasName='" + textBox4.Text + "',
CodeMeli='" + textBox5.Text + "',
Tavalod='" + maskedTextBox1.Text + "',
Address='" + richTextBox1.Text + "',
Madraak='" + textBox7.Text + "',
Shahriye='" + textBox8.Text + "',
Mobile='" + textBox6.Text + "'
where Name=" + textBox1.Text;
Incorrect syntax ')'
private void btnInsert_Click(object sender, EventArgs e) {
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("INSERT INTO Customers(Id,Name,Country,) values (#Id,#Name,#Country)",con);
con.Open();
cmd.Parameters.AddWithValue("#Id",dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Name",dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Country",dataGridView1.Rows[i].Cells[2].Value);
cmd.ExecuteNonQuery();
con.Close();
}
MessageBox.Show("Added successfully!");
}

C# Database Insert (ASP.NET) - ExecuteNonQuery: CommandText property has not been initialized

first time I'm doing an insert from ASP.NET/C# and I'm having a little issue. I keep getting the following error every time this code runs: " ExecuteNonQuery: CommandText property has not been initialized" Does anyone know what this means and how I fix it?
Thanks in advance!
string sqlQuery = "INSERT INTO ATI_LOG_IO (Date, Connect_Time, Disconnect_Time, ATI_Rep, Reason_For_Access, Property_Contact, Case_Number, Comments, Property_ID)";
sqlQuery += "VALUES (#Today, #Connect, #Disconnect, #Rep, #Reason, #Contact, #CaseNum, #Comments, #PropertyID)";
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand dataCommand = dataConnection.CreateCommand())
{
dataConnection.Open();
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText = sqlQuery;
dataCommand.Parameters.Add("#Today", DateTime.Today.ToString());
dataCommand.Parameters.Add("#Connect", txtInDate.Text + " " + fromHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.Add("#Disconnect", txtOutdate.Text + " " + toHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.Add("#Rep", repID);
dataCommand.Parameters.Add("#Reason", txtReason.Text);
dataCommand.Parameters.Add("#Contact", txtContact.Text);
dataCommand.Parameters.Add("#CaseNum", txtCaseNum.Text);
dataCommand.Parameters.Add("#Comments", txtComments.Text);
dataCommand.Parameters.Add("#PropertyID", lstProperties.SelectedValue);
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
}
string sqlQuery = "INSERT INTO ATI_LOG_IO (Date, Connect_Time, Disconnect_Time, ATI_Rep, Reason_For_Access, Property_Contact, Case_Number, Comments, Property_ID)";
sqlQuery += " VALUES (#Today, #Connect, #Disconnect, #Rep, #Reason, #Contact, #CaseNum, #Comments, #PropertyID)";
using (SqlConnection dataConnection = new SqlConnection(connectionString))
{
using (SqlCommand dataCommand = new SqlCommand(sqlQuery, dataConnection))
{
dataCommand.Parameters.AddWithValue("Today", DateTime.Today.ToString());
dataCommand.Parameters.AddWithValue("Connect", txtInDate.Text + " " + fromHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.AddWithValue("Disconnect", txtOutdate.Text + " " + toHrs.Text + ":" + fromMins.Text + ":00");
dataCommand.Parameters.AddWithValue("Rep", repID);
dataCommand.Parameters.AddWithValue("Reason", txtReason.Text);
dataCommand.Parameters.AddWithValue("Contact", txtContact.Text);
dataCommand.Parameters.AddWithValue("CaseNum", txtCaseNum.Text);
dataCommand.Parameters.AddWithValue("Comments", txtComments.Text);
dataCommand.Parameters.AddWithValue("PropertyID", lstProperties.SelectedValue);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
}
Copy-paste should do the trick
This usually means you haven't set the CommandText property, but in your case, you have.
You should try testing that the sqlQuery string is actually not empty at this line:
dataCommand.CommandText = sqlQuery;
P.S. As a "best practice", you may want to consider opening the connection AFTER setting up the SqlCommand object, to minimize the time spent with an open connection:
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText = sqlQuery;
dataCommand.Parameters.Add("#Today", DateTime.Today.ToString());
//...
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
Looking at your string sql query, you're not leaving a space between the "INTO" part and "VALUES" part.
...............Property_ID)";
sqlQuery += "VALUES (#Today, ..............
SHOULD BE:
...............Property_ID)";
sqlQuery += " VALUES (#Today, ..............

Categories

Resources