I create a program to backup the whole DB from SQL server 2014 , i used the code before it was work perfectly on another laptop (was working on it coding with c#).
now i'm trying to backup not work at all this is the code:
1/- SqlConnection:
SqlConnection con = new SqlConnection(WindowsFormsApplication11.Properties.Settings.Default.database1ConnectionString);
2/- textbtn1
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.SelectedPath;
BackupButton.Enabled = true;
}
}
3/- textbtn2 code :
private void BackupButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
try
{
if(textBox1.Text==string.Empty)
{
MessageBox.Show("please enter backup file location");
}
else
{
string cmd = "BACKUP DATABASE [" + database + "] TO DISK='" + textBox1.Text + "\\" + "database" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'";
using(SqlCommand command = new SqlCommand(cmd,con))
{
if(con.State!=ConnectionState.Open)
{
con.Open();
}
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("database backup done successefully");
BackupButton.Enabled = false;
}
}
}
catch
{
}
}
** even this code not work and no message show up :p , don't know why ?
i changed every thing , i created a new class called DBconnect :
class DBconnect
{
public SqlConnection myConn = new SqlConnection(#"Data Source=MYSERVERNAME;Initial Catalog=MYDBNAME;User ID=sa;Password=12345");
public void backup(string name_path)
{
try
{
string query = "Backup Database MYDBNAMEto Disk ='" + name_path + ".bak'";
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = query;
myCommand.Connection = myConn;
myCommand.ExecuteNonQuery();
MessageBox.Show("sauvegarde succès", "sauvegarde", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
}
}
in my form i did this :
DBconnect conn = new DBconnect();
in backup textbtn2 i did this :
string Namefile = textboxBATH.Text + "\\MYDBNAME" + " " + DateTime.Now.ToShortDateString().Replace('/', '-') + "-" + DateTime.Now.ToLongTimeString().Replace(':', '-');
Conn.backup(Namefile);
in this case i faces this erorr message :
Cannot open backup device. Operating system error 5(Access is denied.) BACKUP DATABASE is terminating abnormally.
i thought SQL service might not have permission to the Path where backup bath is supposed to be created . and i create new folder in my Desktop and gave it the permission Read+Write .. and this not work too .. :p
thank you all .
Related
I'm trying to restore a SQL Server database backup with this code:
private void restoreButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
string sqlStmt2 = string.Format("ALTER [MangementSystemBD] [" + database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE [MangementSystemBD] [" + database + "] FROM DISK='" + textBox2.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER [MangementSystemBD] [" + database + "] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
bu4.ExecuteNonQuery();
MessageBox.Show("database restoration done successfully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
But when I execute it I get this error:
For restoring database use this code
public void RestoreDatabaseBackup()
{
ExecuteQuery("EXEC msdb.dbo.sp_delete_database_backuphistory #database_name = 'DatabaseName");
ExecuteQuery("USE MASTER");
OpenFileDialog res = new OpenFileDialog();
res.ShowDialog();
if (res.FileName.ToString() == "")
{
//MessageBox.Show("Select Valid .bak File");
}
else
{
try
{
string s = res.FileName.ToString();
SqlConnection sqlConnection = new SqlConnection(#"Data Source=ServerName;Initial Catalog=yourDatabaseName;Integrated Security=True;Pooling=False");
if (sqlConnection.State == System.Data.ConnectionState.Open)
{
sqlConnection.Close();
}
sqlConnection.Open();
ServerConnection ServerConnection = new ServerConnection(sqlConnection);
Server srv = new Server(ServerConnection);
//Declare a BackupDeviceItem by supplying the backup device file name in the constructor, and the type of device is a file.
BackupDeviceItem bdi = default(BackupDeviceItem);
bdi = new BackupDeviceItem(s, DeviceType.File);
// Define a Restore object variable.
Restore rs = new Restore();
//Set the NoRecovery property to true, so the transactions are not recovered.
rs.NoRecovery = true;
rs.ReplaceDatabase = true;
// Add the device that contains the full database backup to the Restore object.
rs.Devices.Add(bdi);
rs.NoRecovery = false;
// Specify the database name.
rs.Database = sqlConnection.Database.ToString();
// Restore the full database backup with no recovery.
sqlConnection.ChangeDatabase("master");
rs.SqlRestore(srv);
// Inform the user that the Full Database Restore is complete.
srv = null;
MessageBox.Show("Database Restore complete.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
ExecuteQuery is a normal method to run SQL you should make it
Im trying to pass two parameters to my oracle package.
I can get the parameters, but it is not being passed into the database. Every time I run the application it fails to make a connection and goes straight to my try catch method.
Is there something I am doing wrong?
This is what I have so far:
using System.Data.OracleClient;
private void btnGetData_Click(object sender, EventArgs e)
{
GetOrders_OracleCon_GetData(Parameter1,Parameter2);
// when i output or add in a break i can see that the data does come into the Parameter values. However after that it doesnt go to my db
}
public void GetOrders_OracleCon_GetData(Int32 PM1, String PM2)
{
using (OracleConnection objConn = new OracleConnection("Data Source=" + dbcon + "; User ID=" + uid + "; Password=" + pass))
{
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = objConn;
objCmd.CommandText = "PCK_Orders.get_data";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.Add("pm1", OracleType.Number).Value = PM1;
objCmd.Parameters.Add("pm2", OracleType.VarChar).Value =PM2;
objCmd.Parameters.Add("selected_orders", OracleType.Cursor).Direction = ParameterDirection.Output;
try
{
objConn.Open();
OracleDataReader objReader = objCmd.ExecuteReader();
if (objReader.HasRows)
{
GetOrders_GetData(objReader);
btnCancel.Enabled = true;
}
else
{
Timer_ProgBar.Stop();
MessageBox.Show("Orders for this Datedoes not exist", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
GP_ClearAllFields("Y", "Y");
Timer_ProgBar_Initialize(0, "");
}
}
catch (Exception)
{
Timer_ProgBar.Stop();
MessageBox.Show("An error has occured");
// this is the error that i catch but im not sure what is causing it. am i missing something?
Timer_ProgBar_Initialize(0, "");
}
objConn.Close();
}
}
private void okbtn_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Desktop\GameMuseumManagementSystem.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String Email = txtEmail.Text.ToString();
String Password = txtPassword.Text.ToString();
String my_query = "INSERT INTO Member(Member_Name,Member_Password,Member_Email)VALUES('" + Name + "','" + Email + "','" + Password + "')";
OleDbCommand cmd = new OleDbCommand(my_query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
}
I am coding for the member registeration for a guest to use it. I have 3 pieces of data, member_name, member_ID, and password. I coded this and I get an error. My Visual Studio is connected to my MS Access database via the tools, after I write this code, the data can't be stored in Access, what should I do now? Any suggestion?
I developed a POS like application and during testing with 2 PCs I didn't encounter any problems with the speed. It's just a simple LAN cable setup between 2 computers. But when I deployed it in a client, it ran slow.
The client has 1 PC serving as the admin and the main server, and there are 2 more PCs serving as the cashier. All connected in a router. The cashiers are connected to the admin's PC (main server) to retrieve, insert, update and delete data. I just want to ask if there are processes that needs to be done in MySQL or are there anything wrong with my codes when connecting to the database.
Here's my sample code for connecting to the database, I doubt having problems with it as this has been the standard in connecting to a database and adding records. Just in case I might bore you with codes, you can simply jump to the second code I posted, I have a comment there asking if the initialization of my class is correct. Thanks everyone!
class DBConnection
{
private MySqlConnection connection;
private MySqlCommand cmd;
private MySqlDataReader dr;
private DataTable tbl;
private MySqlDataAdapter da;
private DataSet ds;
private string connectionString;
private string server;
private string database;
private string uid;
private string password;
private frmNotifOk myNotification;
public DBConnection()
{
Initialize();
}
private void Initialize()
{
server = "CASHIER";
database = "sampledb";
uid = "root";
password = "samplepassword";
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server.");
break;
}
return false;
}
}
private void CloseConnection()
{
try
{
connection.Close();
}
catch (MySqlException ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
public void AddRecord(String DBQuery, bool showNotif)
{
string query = DBQuery;
bool notify = showNotif;
try
{
if (this.OpenConnection() == true)
{
cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
if (notify)
{
MessageBox.Show("Item successfully added.");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
finally
{
this.CloseConnection();
}
}
And finally, here's how I use the method in a form:
public partial class frmNewCashier : Form
{
private DBConnection dbConnect;
string sampleDataSource= "SELECT * FROM SampleTable";
public frmNewCashier()
{
InitializeComponent();
//Is this the correct place of initializing my DBConnection class?
dbConnect = new DBConnection();
}
private void frmCashier_Load(object sender, EventArgs e)
{
try
{
dgvSearchItems.DataSource = dbConnect.DatabaseToDatagrid(dgvSearchItemsDataSource);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
I put the initialization of DBConnection class in public frmNewCashier(), is this the correct place or should I put it in Load event or somewhere? I'm thinking if this has bearing to the slowness of database. Aside from this question, do you know anything that I might have missed that causes the slowness?
class DBConnect
{
public MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
public void Initialize()
{
server = "localhost";
database = "db_sea_horses";
uid = "root";
password = " " ;
//password = "123";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
public bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{ //0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
public bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
class DBmethods : DBConnect
{
DataSet dataset2;
public void input_sql(string query)
{
try
{
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
int x = cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
catch(MySqlException myex)
{
MessageBox.Show(ex.Message);
}
}
///////////////////////////////////////////////
///// select
/////////////////////////////////////////////
public DataSet output_sql(string query,String table_name)
{
//Open connection
this.OpenConnection();
DataSet dataset = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand(query, connection);
adapter.Fill(dataset, table_name);
//close Connection
this.CloseConnection();
//return list to be displayed
return dataset;
}
}
}
method calling example
1) insert / update / delete statement
DBmethods dbm = new DBmethods();
dbm.input_sql(" you can excute insert / update / delete query");
2) select statement
DataSet ds = dbm.output_sql("select * from storage_bunkers where job_id LIKE '%" + itemname.Text + "%' ", "storage_bunkers");
DataView myView = ((DataTable)ds.Tables["storage_bunkers"]).DefaultView;
dataGridView1.DataSource = myView;
First, try pinging from client machine to server which has installed SQL server. If it is taking too much time then there's problem with network connection.
If not, put a debug point and try debugging then identify the location that taking too long. Then you will able to get a answer.
Also, do not forget to close each and every db connection after using that.
I am new to SQL and trying to create a Database using C#. Here is my Code...
private void CreateDBBtn_Click(object sender, EventArgs e)
{
String connectionString = GetConnectionString();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
String SQLCommand = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'D:\\MyDatabase.mdf'," +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)";
SqlCommand cmd = new SqlCommand(SQLCommand, connection);
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ae)
{
MessageBox.Show(ae.Message);
}
}
private String GetConnectionString()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = #".\SQLSERVER";
builder.AttachDBFilename = #"D:\MyDatabase.mdf";
builder.IntegratedSecurity = true;
builder.ConnectTimeout = 30;
builder.UserInstance = true;
return builder.ConnectionString;
}
but it gives me error that...
Where as D:\MyDataBase.mdf file has size 3.13 MB on my PC.
I completely agree with DJ KRAZE. It would take about two seconds to create that using whatever server manager you have.