creating connection string for attached MDF file - c#

what you see bellow is a part of my WPF project I used it to backup/restore my SQL server database and it works great but; when I want to make a setup file by advanced installer and I move MDF and LDF files created by SQL script to app directory to use in SQL express it doesn't work. Now I want to know what can I do with connection string so that backup/restore prosses can work correctly
private string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFileName=|DataDirectory|\\DBNBO.mdf;Database=DBNBO; Trusted_Connection=Yes;";
private void BtnBackup_OnClick(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
string database = connection.Database;
string query = "Backup Database [" + database + "] To Disk = '" + txtBackup.Text + "\\DB_backup.bak'";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
private void btnRestore_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
string database = connection.Database;
if (connection.State != ConnectionState.Open) connection.Open();
string query1 = string.Format("Alter Database [" + database + "] Set Single_User With Rollback Immediate");
SqlCommand command1 = new SqlCommand(query1, connection);
command1.ExecuteNonQuery();
string query2 = string.Format("Use Master Restore Database [" + database + "] From Disk = '" + txtRestore.Text + "' With Replace");
SqlCommand command2 = new SqlCommand(query2, connection);
command2.ExecuteNonQuery();
string query3 = string.Format("Alter Database [" + database + "] Set Multi_User");
SqlCommand command3 = new SqlCommand(query3, connection);
command3.ExecuteNonQuery();
connection.Close();
}

Related

C# SQL Server database update data

I want to update data in a SQL Server database but something is wrong. My code does not update the database and I don't know what the problem is
if (d.Contains("1"))
{
sql1 = "UPDATE Faucets SET Enabled='0' WHERE FaucetName='" + dataGridView1.Rows[e.RowIndex].Cells[1].Value + "'";
}
else
{
sql1 = "UPDATE Faucets SET Enabled='1' WHERE FaucetName='" + dataGridView1.Rows[e.RowIndex].Cells[1].Value + "'";
}
SqlConnection connect1 = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\faucets.mdf;Integrated Security=True");
connect1.Open();
SqlCommand parancs1 = connect1.CreateCommand();
parancs1.CommandType = CommandType.Text;
parancs1.CommandText = sql1;
parancs1.ExecuteNonQuery();
connect1.Close();

InvalidOperationException: Connection property has not been initialized in update command?

protected void btnUpdate_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
}
This code displays an error like this:
System.InvalidOperationException. ExecuteNonQuery: Connection property has not been initialized.
You need to tell your sql command that use this connection(con) to execute the command(cmd).so use an overloaded constructor of the SqlCommand class that takes 2 parameters(cmdText, connection).
SqlCommand cmd = new SqlCommand("update Students set RegNo='" +
RegNo"',Name='" + Name.Text + "',Address=" + Address.text, con);
But it is also possible, to create an instance of SqlCommand class using the parameter less constructor, and then later specify the command text and connection, using the CommandText and Connection properties of the SqlCommand object as shown below.
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
cmd.Connection = con;
con.Open();
You can use the using statement where the resources are automatically disposed.We don't have to explicitly call Close() method, when using is used. The connection will be automatically closed for us.
int result;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text, con);
con.Open();
result = cmd.ExecuteNonQuery();
}
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
To try to use as following sample code
string constr ="Data Source=localhost;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=1111"
SqlConnection con = new SqlConnection(constr);
I think , in the SQL Command you need to assign the connection
protected void btnUpdate_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
cmd.Connection = con;
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
}
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Student set Name='" + Name.Text + "',Address='" + Address.Text + "'where RegNo=" + RegNo.Text);
cmd.Connection = con;//adding this line my error solved
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
I changed my code like above.

Insert command works without errors in C# but data is not inserted to the MS SQL Server

I am trying to insert data into Microsoft SQL Server DB using C# and the insert command works well and I get no errors or exceptions. But when I check my database in SQL Server there is no effect on the table and the records are not inserted into the table. This is the code that I try:
try
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.Connection = con1;
cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','#" + update.Message.Chat.Username + "','" + req1.Status + "')";
con1.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
continue;
}
I've seen similar questions here and here, but the answers did not fix my problem.
Also when I insert data to the DB manually and run select command like mentioned below, I get the correct answer but for the insert command I do not.
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con2.Open();
SqlDataAdapter da1 = new SqlDataAdapter("select * from Users where ChatID='" + update.Message.Chat.Id.ToString() + "'", con2);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
con1.Close();
Please help me fix this issue.
By the way I know that this kind of insertion is not safe and I'l like to let you know that this is just a demo and I will make it secure against sql injection.
You are not executing your command anywhere.
You need:
cm1.ExecuteNonQuery();
In your code, you are creating a SqlCommand object, then you associate a SqlConnection to it, but in no where you are actually executing the command. Your code should look like:
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.Connection = con1;
cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','#" + update.Message.Chat.Username + "','" + req1.Status + "'";
cm1.ExecuteNonQuery();
con1.Close();
Apart from SQL Injection vulnerability, you should consider enclosing your SqlCommand and SqlConnection object in using statement, that will ensure proper disposal of un-managed resources.

Populating SQL Server Datatable

My program will not update my SQL Server database after executing. When I run my program my DataGridView updates when I insert my information, but it will not update itself in the dataTable.
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES('" + idTextBox.Text + "','" + nameTextBox.Text + "','" + ageTextBox.Text + "')";
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
conn.Open();
cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
this.dataTableTableAdapter.Fill(this.employeeDataSet1.dataTable);
conn.Close();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataTable data = new DataTable();
conn.Open();
adapt.Update(data);
conn.Close();
dataTableDataGridView.DataSource = data;
}
If you created your DataGridView using the designer which added a dataset, bindingsource, and tableadapter, then your DataGridView should be configured correctly out of the box. Try commented out these lines:
//SqlDataAdapter adapt = new SqlDataAdapter(cmd);
//DataTable data = new DataTable();
//conn.Open();
//adapt.Update(data);
//conn.Close();
//dataGridView1.DataSource = data;
I replicated your button_click code and it works locally for me using Sql Express.
Based on your comment i assume the cause is the missing conversion. Using Int32.TryParse you can convert the string to int. Be aware that the ' have to go as well
int id, age;
bool idIsInt = false, ageIsInt = false;
idIsInt = Int32.TryParse(idTextBox.Text, out id);
ageIsInt = Int32.TryParse(ageTextBox.Text, out age);
if(idIsInt && ageIsInt)
{
string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES("
+ id + ",'" + nameTextBox.Text + "',"
+ age + ")";
SqlConnection conn =
new SqlConnection(#"Data Source(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf
;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
conn.Open();
cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
}

Where do I find the databases? Visual Studio and SQL

I have installed Visual Studio Ultimate, and installed the Microsoft SQL Server, and tried to find my way around it, using some tutorials I found on line.
I have successfully compiled and run the following C# code:
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
SqlConnection sql = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=True;User Instance=True");
sql.Open();
SqlCommand command = new SqlCommand("CREATE DATABASE newDatabase;", sql);
command.ExecuteNonQuery();
command.CommandText = "CREATE TABLE newTable (name VARCHAR(20), age INT)";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO newTable VALUES ('John', 29)";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO newTable VALUES ('Jack', 21)";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO newTable VALUES ('Robin', 22)";
command.ExecuteNonQuery();
command.CommandText = "SELECT * FROM newTable;";
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0} is {1} years old.",reader.GetString(0), reader.GetValue(1));
}
reader.Close();
sql.Close();
Console.ReadLine();
}
}
}
This will produce the right output, but now I want to actually see the newDatabase data-base. So I search for the keyword 'sql', and found the 'Microsoft SQL Server Managment Studio', and opened it.
Unfortunately, I couldn't find my database there under Databases:
Where is it hiding and how can I find it?
You need to attach this new database. On Databases, "right-click", and attach Database. Browse to the C# project folder defined when you created your project with visual studio and you will find it in the folder.
Update
In case you want to define the path directly to avoid searching you can have look on this example which might help you:
String str;
SqlConnection myConn = new SqlConnection ("Data Source=.\\SQLEXPRESS;Integrated Security=True;User Instance=True");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
Console.Write(ex.ToString());
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}

Categories