I have a program that stores user projects as databases. Naturally, the program should allow the user to create and delete the databases as they need to. When the program boots up, it looks for all the databases in a specific SQLServer instance that have the structure the program is expecting. These database are then loaded into a listbox so the user can pick one to open as a project to work on.
When I try to delete a database from the program, I always get an SQL error saying that the database is currently open and the operation fails. I've determined that the code that checks for the databases to load is causing the problem. I'm not sure why though, because I'm quite sure that all the connections are being properly closed.
Here are all the relevant functions. After calling BuildProjectList, running "DROP DATABASE database_name" from ExecuteSQL fails with the message: "Cannot drop database because it is currently in use". I'm using SQLServer 2005.
private SqlConnection databaseConnection;
private string connectionString;
private ArrayList databases;
public ArrayList BuildProjectList()
{
//databases is an ArrayList of all the databases in an instance
if (databases.Count <= 0)
{
return null;
}
ArrayList databaseNames = new ArrayList();
for (int i = 0; i < databases.Count; i++)
{
string db = databases[i].ToString();
connectionString = "Server=localhost\\SQLExpress;Trusted_Connection=True;Database=" + db + ";";
//Check if the database has the table required for the project
string sql = "select * from TableExpectedToExist";
if (ExecuteSQL(sql)) {
databaseNames.Add(db);
}
}
return databaseNames;
}
private bool ExecuteSQL(string sql)
{
bool success = false;
openConnection();
SqlCommand cmd = new SqlCommand(sql, databaseConnection);
try
{
cmd.ExecuteNonQuery();
success = true;
}
catch (SqlException ae)
{
MessageBox.Show(ae.Message.ToString());
}
closeConnection();
return success;
}
public void openConnection()
{
databaseConnection = new SqlConnection(connectionString);
try
{
databaseConnection.Open();
}
catch(Exception e)
{
MessageBox.Show(e.ToString(), "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void closeConnection()
{
if (databaseConnection != null)
{
try
{
databaseConnection.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
The SqlConnection class polls the actual database connection. If you close the SqlConnection, the connection is returned to the Connection pool. To prevent this behaviour, set SqlConnection.Pooling = false;.
edit
John seems to be more to the point here. But you might have to keep polling in mind as well.
Two comments. First off, you should use a using statement and your could will be much cleaner.
More on topic, you are connecting to the database when you are trying to drop it! Connect to the master database instead.
Related
How to restore a database from SQL Server 2012?
This is my code:
private void [connTes()][1]
{
try
{
conString = "server=.\\SQLEXPRESS;database=db_datatestproject;user=admin;password=123;Integrated Security=True";
connnn = new SqlConnection(conString);
connnn.Open();
}
catch
{
}
}
private void button1_Click(object sender, EventArgs e)
{
connTes();
try
{
if (txtlocation.Text == "")
{
MessageBox.Show("select database");
return;
}
else
{
string databesing = connnn.Database.ToString();
string a = "ALTER DATABASE " + databesing + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
a += "RESTORE DATABASE "+databesing+" FROM DISK ='"+txtlocation.Text+"' WITH REPLACE;";
SqlCommand cmd = new SqlCommand(a, connnn);
SqlDataReader dr = cmd.ExecuteReader();
connnn.Close();
connnn.Dispose();
MessageBox.Show("done restored");
}
}
catch(SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
This is the error I get:
RESTORE cannot process database 'db_testproject' because it use by the session. It is recommended that the master database be used when performing this operation. RESTORE DATABASE is terminating abnormally.
How to fix this error?
Any help is much appreciated.
Thank you.
Add
USE MASTER;
GO
to the start of your TSQL restore command.
You need to be in another database and not the one you are restoring.
Also please note #marc_s's comment: "Since you're not getting back any data from that SqlCommand, use ExecuteNonQuery() instead of ExecuteReader()"
I have the following SQL helper class:
public class SqlHelper
{
SqlConnection cn;
public SqlHelper(string connectionString)
{
cn = new SqlConnection(connectionString);
}
public bool isConnection
{
get
{
if (cn.State == System.Data.ConnectionState.Closed)
cn.Open();
return true;
}
}
}
I also have two connection strings:
string connectionString = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", Variables.setDb1ServerName, Variables.setDb1Name, Variables.setDb1User, Variables.setDb1Password);
string connectionString2 = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", Variables.setDb2ServerName, Variables.setDb2Name, Variables.setDb2User, Variables.setDb2Password);
What I want to do is create two buttons that will check if the respective connection is active.
My attempt is below - button one:
private void txtConnection1_Click(object sender, EventArgs e)
{
string connectionString = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", Variables.setDb1ServerName, Variables.setDb1Name, Variables.setDb1User, Variables.setDb1Password);
try
{
SqlHelper helper = new SqlHelper(connectionString);
if (helper.isConnection)
MessageBox.Show("Конекцијата е успешна", "Порака", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Порака", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I've also create a second button, that connects to ConnectionString2 with SqlHelper helper2 = new SqlHelper(connectionString);
The code compiled alright. But I'm getting errors in the actual usage. One of the connections is diagnosed as active, while the second one produces a error.
Why question is.. can I reference two connection strings to a single sql helper class? If yes, any ideas where I might be making a mistake?
Update:
So this is the error that I am receiving. But if I restart the application and try the same connection first, I will be receiving a positive indicator.
Right now, my professor requires me to implement a case study using ADO.NET to save data into SQL Server. I have already created a database and tables in SQL Server and I'm trying to create some forms in Visual Studio by C# ADO.NET. I write according to a YouTube video. But I don't know why I cannot save my data to database successfully.
The result as I write my code like this.
Any help would be appreciated.
namespace casestudy
{
public partial class Form2 : Form
{
SqlConnection vcon2 = new SqlConnection(#"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
vcon2.Open();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
{
string vsql = string.Format("insert into Calluser values ({0}, '{1}', '{2}', {3})", Int32.Parse(txtUserID.Text), txtFName.Text, txtLName.Text, Int32.Parse(txtZoneID.Text));
SqlCommand vCom = new SqlCommand(vsql, vcon2);
try
{
vCom.ExecuteNonQuery();
vCom.Dispose();
MessageBox.Show("The User Information stored.");
txtZoneID.Text = "";
txtLName.Text = "";
txtFName.Text = "";
txtUserID.Text = "";
txtUserID.Focus();
}
catch (Exception ex)
{
MessageBox.Show("error.occured" + ex.Message);
this.Dispose();
}
}
}
}
Can you add a check to see if the connection is actually open and if not reopen it just before you call the ExecuteNonQuery()
if (vcon2.State != ConnectionState.Open)
{
vcon2.Open();
}
vCom.ExecuteNonQuery();
Opening the connection when the application or form opens is probably not the best approach. You want to open the connection right before you execute your sql and close it as soon as possible.
That being said, I recommend removing the code from the Form2_Load event. And do everything in the button1_Click or another method you call from there. Even better would be to have a class or component that does the data access for your application. Also use a using statement as it will ensure resources are disposed even if an exception is thrown.
using (SqlConnection connection = new SqlConnection(#"Data Source=SOPHIA-PC\SQLEXPRESS;Initial Catalog=casestudy;Integrated Security=True");))
{
SqlCommand command = new SqlCommand(vsql, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
Some info on the using statement:
http://www.dotnetperls.com/using
https://msdn.microsoft.com/en-us/library/yh598w02.aspx
I want open WPF program, then SQL Server database is off and when database is back online, WPF should auto connect to the database. If I restart SQL Server, keep alive program and try connect to database until connection is available. Should I catch the exception and then repeat something?
I try restart application then I got exception, but anyway my program crash and stop working.
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
}
catch (SqlException ex)
{
//how stop crash? //
//System.Windows.Forms.Application.Restart();
return ex.ToString();
}
finally
{
connection.Close();
}
}
The thing to do is to centralize the creation of connections in a single static method for your entire application.
public static SqlConnection getConnection()
{
string conn = string.Empty;
conn = System.Configuration.ConfigurationManager.ConnectionStrings["quality"].ConnectionString;
SqlConnection aConnection = new SqlConnection(conn);
return aConnection;
}
In your code,every time you use a connection try this :
public int test()
{
SqlConnection conn = null;
try
{
try
{
conn = StaticContext.getConnection();
conn.Open();
//TODO OPERATION
}
catch (Exception e)
{
//return ex.ToString();
return -1;//MY_ERROR_CODE;
}
}
finally
{
conn.Close();
}
return 1//MY_SUCCES_CODE;
}
When you call DB method manage so the error:
if (test() == -1)
{
//MESSAGE BOX ERROR OR OTHER
}
So i been trying to connect C# windows from to MYSQL database, i tryed many different methods that i found online but none seems to be working. here is my code please help (keep in mind this is the first time i use database before).
Here is the connecting class
class DbConnect
{
public static void DBConnect()
{
string connstr =
"server=localhost;user=root;database=login;port=3306;password=Password";
MySqlConnection conn = new MySqlConnection(connstr);
try
{
conn.Open();
}
catch
{
Console.WriteLine("went rong");
}
}
}
Here is the windows form im using
private void btnenter_Click(object sender, EventArgs e)
{
DbConnect.DBConnect();
MySqlCommand query = new MySqlCommand("INSERT INTO logininfo (username,
password) VALUES(#username, #password");
try
{
query.Parameters.AddWithValue("#username", txtusername.Text);
query.ExecuteNonQuery();
MessageBox.Show("S");
}
catch (Exception )
{
MessageBox.Show("something went wrong");
}
finally
{
DbConnect.DBClose();
}
}
User is passed in MySQL connection string using Uid. So your connection string should be like:
"server=localhost;Uid=root;database=login;port=3306;password=tro63jans";
You may see: MySQL connection string.
You should also catch exception in some object, so that you can get the details about the exception. Currently you are not showing any useful message from your exception.
catch (Exception ex) //at least
{
MessageBox.Show("something went wrong: " + ex.ToString());
}
One problem you have here is you're not setting the Connection property of your MysqlCommand to the MySqlConnection you're making earlier.
Change DBConnect() to return your MySqlConnection.
Set your MySqlCommand's Connection property to the returned value.
PSEUDO-CODE
MySqlConnection conn = DBConnect.DBConnect();
MySqlCommand command = new MySqlCommand(commandStr, conn);
command.ExecuteNonQuery();
conn.Close();