When I run the application, are all forms in the app loaded/initialized even though I have not opened them yet? (I.E. Form.Show)
this is how I closed the connection in the login form:
if (usertype == "UT1") //admin rights
{
//GET LOGGED USER
Home_Admin homeAdmin = new Home_Admin();
homeAdmin.SetUsername(username);
cString.Close();
this.Close();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(OpenHomeAdmin));
t.Start();
}
And how I got to the back up form from Home_Admin's menu strip
private void backUpToolStripMenuItem_Click(object sender, EventArgs e)
{
BackUp BackUpForm = new BackUp();
BackUpForm.Show();
}
I am trying to create a back up of my database and it works perfectly if I run only the back up form. If I start the app from the very beginning, it says back up failed the database is in use. I already closed the connection from login to the form where I will launch the back up form and even set a
if(conn.State = connectionState.Open)
{
conn.close();
}
prior to the back up procedure. Is there any way I can just kill all connections to the SQL database > back up > and then restore the connections?
BACK UP CODE
public void BackupDatabase(String destinationPath)
{
SqlConnection cString = new SqlConnection();
cString.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\MY_THESIS\\WORKING FILES\\NNIT-RMS.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
if (cString.State == ConnectionState.Open)
{
cString.Close();
}
try
{
//MY SERVER
String userName = "NNIT-Admin";
String password = "password";
String serverName = #"RITZEL-PC\SQLEXPRESS";
ServerConnection connection = new ServerConnection(serverName, userName, password);
Server sqlServer = new Server(connection);
Backup BackupMgr = new Backup();
BackupMgr.Devices.AddDevice(destinationPath, DeviceType.File);
BackupMgr.Database = "NNIT DB";
BackupMgr.Action = BackupActionType.Database;
BackupMgr.SqlBackup(sqlServer);
MessageBox.Show("Back up saved!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " " + ex.InnerException);
}
}
FORM LOAD
private void BackUp_Load(object sender, EventArgs e)
{
string date = DateTime.Now.Day.ToString();
string year = DateTime.Now.Year.ToString();
string month = DateTime.Now.Month.ToString();
Filename_txt.Text = "NNIT-RMSDB_" + month + date + year;
}
Error message
http://img824.imageshack.us/img824/8541/error1lj.jpg
In this piece of code:
SqlConnection cString = new SqlConnection();
cString.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\MY_THESIS\\WORKING FILES\\NNIT-RMS.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
if (cString.State == ConnectionState.Open)
{
cString.Close();
}
You are instantiating a new connection and never opening it. The code in the if clause will never be hit.
Your mistake is assuming that the new connection is the only one - there may be multiple connections (opened in other forms and never properly closed) - some not even from your application (for example, using SQL Server Management Studio - having an open query window to your database will mean there is an open connection).
The best solution for to kill all connections to db is to take it offline, other solutions almost fail
using (SqlConnection sqlcnn = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=True"))
{
SqlCommand sqlcmd = new SqlCommand("ALTER DATABASE DB_NAME SET OFFLINE WITH ROLLBACK IMMEDIATE", sqlcnn);
sqlcnn.Open();
sqlcmd.ExecuteNonQuery();
sqlcnn.Close();
}
Add the above code before your backup or restore code and then your backup or restore will work even if you have open connections to your db.
Related
Through the information I have found searching here on stackoverflow, I have what I think is 90% of this solved but because of how OleDbConnection is converted to define SqlConnection, the call to the class with the connection and test script wants definition I am unsure how to provide.
I've used these pages to get what I have so far
How to create an SqlConnection in C# to point to UDL file
Calling an SQL Connection method in C#
private static string CONNECTION_NAME = #"C:\Temp\DisplayDB.udl";
public static class MyConnection
{
public static SqlConnection GetSqlConnection()
{
var udlInfo = new OleDbConnection($"File Name={CONNECTION_NAME}");
return CreateSqlConnection(udlInfo);
}
public static SqlConnection CreateSqlConnection(OleDbConnection udlInfo)
{
try
{
string CONNECTION_STRING = $"Database={udlInfo.Database};Server={udlInfo.DataSource};User ID=User;Password=13245;Integrated Security=True;connect timeout = 30";
var connection = new SqlConnection(CONNECTION_STRING);
connection.Open();
return connection;
}
catch
{
Console.WriteLine($"{CONNECTION_NAME} Not found");
return null;
}
}
}
private void DBCheck()
{
// The line below is my issue, mouseover error of ".CreateSqlConnection"
// says there is no argument given that corresponds to the required
// formal parameter 'udlInfo' of
// 'MainWindow.MyConnection.CreateSqlConnection(OleDbConnection)'
using (var con = MyConnection.CreateSqlConnection())
{
con.Open();
var command = new SqlCommand("IF DB_ID ('CodeTest') IS NULL " +
"BEGIN " +
"USE MASTER " +
"CREATE DATABASE CodeTest" +
" END", con);
var reader = command.ExecuteReader();
reader.Close();
con.Close();
}
}
I expect the WPF to use the Database and Server from the UDL file to make the SqlConnection so I can run queries and commands. I understand the security part of UDL in plain text but I do not want hard coded values as this application will be used in various environments nor do I want those values to need definition on each launch of the app.
I developed a C# program for Windows-CE platform. The program open and close the connection to the database for every single interaction. See the code below.
Button click:
private void btnStkIn_Click(object sender, EventArgs e)
{
formStockIn = new frmStkIn();
formStockIn.Show();
}
Select Data:
try
{
using (SqlConnection sqlConn = new SqlConnection(<connection-string>))
{
sqlConn.Open();
//Execute command
SqlCommand sqlCmd = new SqlCommand(<Select Query>, sqlConn);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
<Statement here>
}
}
}
catch
{
//SQL command error
itemDT.ErrorMessage = "Select process is failed.Please contact system admin.";
itemDT.Result = 12;
}
Update Data:
try
{
using (SqlConnection sqlConn = new SqlConnection(<connection-string>))
{
sqlConn.Open();
//Execute command
SqlCommand sqlCmd = new SqlCommand(<Update Query>, sqlConn);
if (sqlCmd.ExecuteNonQuery() <= 0)
{
//No row affect
return -99;
}
else
{
//Completed
return 0;
}
}
}
catch
{
//Sql command error
return 99;
}
I would like to connect to database once (when the form in shown) and then do select, Insert, Update the data using the same connection and close the connection when I close the screen. At run-time, some screen can select-update more than once.
What should I do?
What you are doing is fine. It is good practice to keep the connection open for the shortest time possible and then disposing it. This is what you are doing and that's good.
If you keep it open and the user goes off on lunch or vacation and clicks nothing else, you are keeping a connection for no good reason.
If you need to do multiple things at the same time, then open one connection and execute the queries and then close the connection right away.
private void button1_Click(object sender, EventArgs e)
{
string usernames = textBox1.Text;
string passwords = textBox2.Text;
string emailid = textBox5.Text;
string telno = textBox6.Text;
string connectionstring = "Data Source=|DataDirectory|\\libdb.sdf; Persist Security Info=False ;";
using (SqlCeConnection con = new SqlCeConnection(connectionstring))
{
con.Open();
using (SqlCeCommand Query = new SqlCeCommand("INSERT INTO Registers " + "(usernames,passwords,emailid,telno) " + "VALUES (#usernames,#passwords,#emailid,#telno)", con))
{
Query.Parameters.AddWithValue("#usernames", usernames);
Query.Parameters.AddWithValue("#passwords", passwords);
Query.Parameters.AddWithValue("#emailid", emailid);
Query.Parameters.AddWithValue("#telno", telno);
Query.ExecuteNonQuery();
}
MessageBox.Show("QueryExecuted");
con.Close();
MessageBox.Show("Closedconnecrion");
con.Dispose();
MessageBox.Show("disposed");
this.Close();
/*string conString = "Data Source=" +
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"MyAppData\\database.sdf") + ";Password=yourPassword;";
even this method dosent works */
}
}
}
on executing this code I find it executes successfully. But when I go and check the database, I find the entries empty...
I even tried refreshing database..
I didn't find problem in connectivity.
Query no error executed successfully.
The problem is I didn't find result or the data I gave as input in database.
Please be descriptive with code eg and mail to scarlet.gabriel#gmail.com
Test your connection with the database first, You can get the connection string by creating the udl file.
create a textfile and savaas it with the extension udl (example connection.udl).
double click and run this file.
a window will be opened where you can get the option for getting the connection string.
after testing the connection, close this window and open this file with a note pad.
copy the connection string and paste it in the below statement.
string connectionstring =" paste here";
How can you be sure if the connection is open and has done the job? Use try... catch block to catch if any error occurs:
using (SqlCeConnection con = new SqlCeConnection(connectionstring))
{
try{con.Open();}
catch(Exception ex)
{
// database connection error. log/display ex. > return.
}
if(con.State==ConnectionState.Open)
{
using (SqlCeCommand Query = new SqlCeCommand("INSERT INTO Registers " + "(usernames,passwords,emailid,telno) " + "VALUES (#usernames,#passwords,#emailid,#telno)", con))
{
Query.Parameters.AddWithValue("#usernames", usernames);
Query.Parameters.AddWithValue("#passwords", passwords);
Query.Parameters.AddWithValue("#emailid", emailid);
Query.Parameters.AddWithValue("#telno", telno);
try{
Query.ExecuteNonQuery();
}
catch(Exception ex)
{
// database communication error. log/display ex
}
}
MessageBox.Show("QueryExecuted");
}
if(con.State==ConnectionState.Open)
{
try{con.Close();}
catch{}
}
}
Instead of using connectionstring = "Data Source=|DataDirectory|\libdb.sdf; Persist Security Info=False ;"; Please try to use absolute path like
connectionstring = "Data Source=C:\Users\chandra\Documents\Visual Studio 2010\Projects\Window\LMS\AppData\LMSDatabase.sdf;Persist Security Info=False;";
I hope this will work.
Thanks
i was making a simple windows application form, to register some people in a database, so i made a connection class there is it:
public void Query_send(string cmd)
{
String config = "server=127.0.0.1;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = config;
conn.Open();
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}
and then in the BUTTON to give the informations for the MySql i use this:
private void button1_Click(object sender, EventArgs e)
{
Query instance = new Query();
instance.Query_send("INSERT INTO `tbcliente`(`codCliente`, `name`, `cpf`, `telephone`) VALUES ([" + textBox1 + "],[" + textBox2 + "],[" + textBox3 + "],[" + textBox4 + "])");
}
i always get the error with the connection when i click the register button, may someone help me or give me a link of a tutorial that teaches the correct way of doing this?
Thanks, Iago.
My guess is that you need to wrap the VALUES clause results in single quotes as the SQL you are generating will be invalid.
VALUES ('" + textbox1 + "')
Brackets are only required when referring to table or column names. Not when you're referring to string literals.
Odd question, but have you tried applying a password to the database? Depending on the version of MySQL, I have had some issues with leaving the root password unassigned (on local machine you can be safe and just assign 'root' as the password as well). Another option would be to create a user account with permissions and try connection with those credentials.
Not sure if that will help, but it's process of elimination.
Also not sure if method was work in process, but even if it connected there was no execute command against the database.
public void Query_send(string cmd)
{
String config = "server=localhost;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn.Open();
comm.ExecuteNonQuery(); '--this was missing
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}
I am developing a program where I need to make a settings form for my database connection. I stopped at how to set the connection string from textboxes. Here is my code:
In the settings form:
public string adresa_servera()
{
return textBox1.Text;
}
The text in this textbox is: MICHAL-PC\SQLEXPRESS
In my main Form I use:
db_nastavenia nastavenia = new db_nastavenia(); //db_nastavenia is the name of the settings Form
string x = nastavenia.adresa_servera();
SqlConnection databaza = new SqlConnection();
databaza.ConnectionString = "Data Source=" + x + ";Initial Catalog=ZBERUDAJOVTEPLA;Persist Security Info=False;User ID=sa; password=diplomovka";
To x I load text from the textbox of the settings Form.
When I try it by manually typing the connection string like this, it works well:
databaza.ConnectionString = "Data Source=MICHAL-PC\\SQLEXPRESS;Initial Catalog=ZBERUDAJOVTEPLA;Persist Security Info=False;User ID=sa; password=diplomovka";
Michal, if this is the whole code and you don't have set a default value for your textbox, it's no surprise it isn't working. You need to retrieve the value while reacting on some event, for example when you push some button... Or maybe monitor OnTextChanged event...
This example shows you create some form and immediately try to retrieve a value. That won't work, because the textbox has no value yet.
Edit:
Those double-double slashes are causing you these problems. Don't know where it is applying this escaping logic, it may be some setting you set, but there's an easy solution:
string x = nastavenia.adresa_servera().Replace("\\", "\");
Please let me know if this helped you.
Hi you can do something like this:
try
{
string x = TextBox1.Text;
string Connection ="Data Source=" + x + ";Initial Catalog=ZBERUDAJOVTEPLA;Persist Security Info=False;User ID=sa; password=diplomovka";
using (var conn = new SqlConnection(Connection))
{
using (var cmd = new SqlCommand("Select * from Yourtable", conn))
{
try
{
conn.Open();
}
catch (SqlException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
Best Regards