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.
Related
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
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();
i have a problem with this c# code. I need to connect it to mysql, localhost database, Please give me the correct code to [connetionString = "Data Source=ServerName;Initial Catalog=root;User ID=root;Password="; ] connect to the localhost.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
**connetionString = "Data Source=ServerName;Initial Catalog=localhost;User ID=root;Password=";**
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
It should look a little more like this:
connetionString = "Data Source=localhost;Initial Catalog=<Name of the Database>;User ID=root;Password=";
The data source property is where you put the network location, the initial catalog is the name of the database (in mysql).
Edit:
However, I believe you'll need the mysql libraries, which I notice you're not using at the beginning.
Get them from here: http://dev.mysql.com/downloads/connector/net/
The Data.SqlClient namespace is typically how you'd connect to MSSQL.
it seems you have tagged MySql connection, so preferably you want to use the mysql connection. Which you can download / install here: http://dev.mysql.com/downloads/connector/net/
Also it is wise to use the try-catch-finally approach. So that when the connection opens, and some exception occurs, the connection will always close afterwards.
As another addition, you could put the connectionstring in an App.Config or Web.Config so that you have the connectionstring available in all your files, and only have to adjust it in one place.
hope this will help you
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient; //using the mysql dll
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=localhost;Initial Catalog=myDb;User ID=MyUser;Password=MyPass";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
MessageBox.Show(ex.Message); //shows what error actually occurs
}
finally
{
cnn.Close();
}
}
}
}
You are using System.Data.SqlClient in your connection which I think used for SQL Server. Your connection string is also not for MySQL Database. Try this one.
using System.Data.Odbc;
string connectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost;
DATABASE=dbname; UID=myuserid; PASSWORD=mypassword;OPTION=3; POOLING=false;";
OdbcConnection DBCon = new OdbcConnection(connectionString);
if (DBCon.State == ConnectionState.Open)
{
DBCon.Close();
}
DBCon.Open();
MessageBox.Show ("Connection Open ! ");
DBCon.Close();
Change the ODBC Driver version depending on what you are using.
Change the DATABASE, UID and PASSWORD value.
Here is the code you need
private void btnConnect_Click(object sender, EventArgs e)
{
string MyConStr = "Server=localhost;Database=YourDB;Username=YourUsername;Password=YourPassword";
MySqlConnection conn = new MySqlConnection(MyConStr);
conn.Open();
if (conn.State == ConnectionState.Open)
{
MessageBox.Show("Connection Opened Successfully");
conn.Close();
}
else
{
MessageBox.Show("Error Connecting to DataBase");
}
}
I got a problem. I stack!
Don't know if i need a new class for it!
i want a methode for closing the connection via a Button click.
I already created the constructor:
public string Server;
public string Username;
public string Pwd;
public string DB;
MySqlConnection conn;
string ConnString;
public DBVerb(string eServer, string eUsername, string ePwd, string eDB)
{
this.Server = eServer;
this.Username = eUsername;
this.Pwd = ePwd;
this.DB = eDB;
}
And this two methods:
public void Connect(System.Windows.Forms.Label lblStatus)
{
try
{
ConnString = String.Format("server={0};user id={1}; password={2}; database={3}; pooling=false",
this.Server, this.Username, this.Pwd, this.DB);
conn = new MySqlConnection();
conn.ConnectionString = ConnString;
if (conn != null)
conn.Close();
conn.Open();
if (conn.State == ConnectionState.Open)
{
lblStatus.Text = String.Format("Verbindung zu {0} user: {1} Zeit: {2}", this.Server, this.Username, DateTime.Now.ToString());
}
else
{
MessageBox.Show("Felher");
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "Fehler:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void ClConnect()
{
conn = new MySqlConnection();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
Here I'm calling the Methode:
private void cmdHerstellen_Click(object sender, EventArgs e)
{
string lServer = txtBServ.Text;
string lUID = txtBUid.Text;
string lPawd = txtBPass.Text;
string lDB = txtBDat.Text;
DBVerb VerbindungHerstellen = new DBVerb(lServer, lUID, lPawd, lDB);
VerbindungHerstellen.Err();
VerbindungHerstellen.Connect(lblStatus);
}
private void cmdAbbr_Click(object sender, EventArgs e)
{
}
If i call the Method ClConnect() than I have to give the arguments for the parameter, but I already did, so it don't work.
Any idea how to do it?
You are storing your dbconnection as a field in your class. When you want to close it you don't want to assign a new connection object to it with conn = new MySqlConnection(); and instead just want to remove that line and replace it with a check to see if conn is null or not. If its null then no work needs to be done (or maybe its an error) and if its not null then you can check if it is open and close if appropriate.
You probably also want to be careful of where you are creating new objects in the connect method. If conn already exists you probably don't want to (or need to) create a new connection object.
My last comment is that there is something wrong sounding about the user needing to click a button to close your connection. That should be soemthign the code worries about and not the user. However, I obviously don't know what you are doing with this so I can't say it is definitely wrong, just that it feels a bit wrong. :)
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.