How to back up SQL Server database via Winforms C# - 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();
}
}

Related

'ExecuteNonQuery: Connection property has not been initialized.'

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();

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
}
}

Data is not inserted in database table from windows form

I am working on a Desktop application. I developed a form in which user enters data. When he clicks the submit button the data is saved in a database name PakReaEstat. The problem is the data is not inserted in the table and I get an error: SqlException was Unhandled.
When I click the Submit button it prompts error.
The code behind the button is as following:
protected void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo");
con.Open();
SqlCommand cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime)" +
"values (" + Convert.ToInt32(textBox1.Text) + ",'" +
textBox2.Text + "','" +
textBox4.Text + "'," +
textBox5.Text + "," +
textBox6.Text + "," +
textBox7.Text + "," +
textBox8.Text +
"," + textBox3.Text + ")", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Insertion successfully done");
}
Check you connection string and the SQL insert statement.
I recommend that you use sql parameters instead of the the textbox text property as value directly.
Beacause this is a common vulnerability, called SQL injection.
I also recommend to use using statement to ensure the connection is closed.
using (var con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo"))
{
con.Open();
using (var cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime)" + "values (#Application#,#LDAReg#, ... )", con))
{
cmd.Parameters.AddWithValue("#Application#", Convert.ToInt32(textBox1.Text));
cmd.Parameters.AddWithValue("#LDAReg#", textBox2.Text);
// add the other parameters ...
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Insertion successfully done");
There is problem in your SqlConnection
Make sure that your connection string is correct
SqlConnection con = new SqlConnection("Data Source=ali-pc/sqlexpress.PakEstateAgency.dbo");
It should come like
SqlConnection con = new SqlConnection("Data Source=ADMIN3-PC;Initial Catalog=master;Integrated Security=True");
Always put your code in try... catch block if you are doing transaction with datatbase
If your connetion to databse is established and no issue there then
You are missing single quotes on last five textboxes. I suppose that last five columns are of type nvarchar in ur datatbse
change command to
SqlCommand cmd = new SqlCommand("insert into ClientINFO(Application#,LDAReg#,Size,Name,SDW/O,CNIC,Address,Image,giventime) values (" + Convert.ToInt32(textBox1.Text) + ",'" + textBox2.Text + "','" + textBox4.Text + " ','" + textBox5.Text + "','" + textBox6.Text+ "','" +textBox7.Text+ "','"+textBox8.Text +"','"+textBox3.Text+"')", con);

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