Connection to SQL Server 2008 R2 isn't working - c#

I tried to test if my application is connected to the local database. I don't get any errors, so couldn't quite figure out why it's not working. I only get "no connection" output. I tried to debug it but get connection = null. I have SQL Server 2008 R2 (mixed authentication) and Visual Studio 2008 sp1. I tried connecting using both Windows and SQL Server authentication however neither worked.
This is my web.config file.
<connectionStrings>
<add name="MyDbConn"
connectionString="Data Source=local;Initial Catalog=Sample;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Default.aspx.cs
public partial class _Default: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTestDb_Click(object sender, EventArgs e)
{
try {
SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=Sample; Integrated Security=SSPI");
connection.Open();
if (connection != null && connection.State == ConnectionState.Closed) {
Response.Write("Connection OK!");
connection.Close();
} else {
Response.Write("No Connection!");
}
} catch {
Response.Write("No Connection!");
}
}
}

//Try this
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDbConn"].ToString());
protected void btnTestDb_Click(object sender, EventArgs e)
{
try {
con.Open();
if (con.State == ConnectionState.Open)
{
Response.Write("Connection Open");
}
else
{
Response.Write("Connection Closed");
}
con.Close();
} catch {
Response.Write("No Connection!");
}
}

You have some problems in your code that tries to open the connection.
When you try to call connection.Open, the result is an exception if you have problems or simply a connection with its ConnectionState=Open.
Your code instead gives the "Connection OK" message if the ConnectionState is closed, but of course, having just called Open, and if you don't have problems, then the ConnectionState is open.
You could try this code....
protected void btnTestDb_Click(object sender, EventArgs e)
{
string result = TestConnection();
Response.Write(result);
}
private string TestConnection()
{
try
{
using(SqlConnection connection = new SqlConnection("...."))
{
connection.Open();
return "Connection opened correctly";
}
}
catch(Exception ex)
{
return "Error opening the connection:" + ex.Message;
}
}

The written ado.net code will open the connection for sure, but I doubt the connection string will do. Choose appropriate connectionstring from this dedicated site.

Related

Display a successful message after connecting to SQL Server

I'm using the following code in C# to connect to my SQL Server which works fine. But I would like to display a message to the user saying that if the connection was either successful or not and don't know how to do that. Could anyone help me?
This is my code:
string cs = "Data Source=IS020114\\CODRINMA;Initial Catalog=gcOnesti;Integrated Security=True";
private void conectareToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
}
}
catch (Exception er) {
MessageBox.Show(er.Message);
}
}
You provided the answer yourself. Try the following code:
string cs = "Data Source=IS020114\\CODRINMA;Initial Catalog=gcOnesti;Integrated Security=True";
private void conectareToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
MessageBox.Show("Connection successful !!");
}
}
catch (Exception er) {
MessageBox.Show("Connection unsuccessful..");
}
}
I'm not sure exactly what you want and I'm not sure if you have any Control that you want to publish the message in, but a simple messagebox would be like this:
string cs = "Data Source=IS020114\\CODRINMA;Initial Catalog=gcOnesti;Integrated Security=True";
private void conectareToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
MessageBox.Show("Yay! You're connected!");
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}

ADO.NET programming says error occured - ExecuteNonQuery requires an open and available connection

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

how do i connect my app.config connection string to my code

private void Form1_Load(object sender, EventArgs e)
{
try
{
con.Open();
DataTable dt = con.GetSchema("TABLES").AsEnumerable().Where(x => x.Field<string>("TABLE_TYPE") == "TABLE").CopyToDataTable();
foreach (DataRow r in dt.Rows)
comboBoxTabel.Items.Add(r["TABLE_NAME"].ToString());
}
catch (Exception ex)
{
MessageBox.Show("Error met databank connectie." + Environment.NewLine + ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
What I want is that I'm able to make a connection string inside my code WITHOUT a path that connects to the connection string inside of the app.config(here is the path).
Use the configuration manager
You should use the ConfigurationManager to do this
var cstr = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString
using(var connection = new OleDbConnection(cstr))
{
//do stuff with connection
}
Your error has nothing to do with the connection string
Please read the error carefully, you are trying to preform operation on a string, your variable con, you should be doing the operations on the object connection based off of the image you provided

how to connect to localhost with this code?

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");
}
}

close opened connection using c#

Am using the below code in a class file and access this function for open the connection it return true. I want to close this connection state .I can't do this. please help me to do this.
common.cs
=========
public static bool DBConnectionStatus()
{
try
{
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|db_gym.mdb; Jet OLEDB:Database Password=gym_admin";
using (OleDbConnection conn = new OleDbConnection(conString))
{
conn.Open();
return (conn.State == ConnectionState.Open);
}
}
catch (OleDbException)
{
return false;
}
catch (Exception)
{
return false;
}
}
protected void btn_general_Click(object sender, EventArgs e)
{
try
{
bool state = common.DBConnectionStatus();
if(state == true)
{
// Some operation
}
// I want to close this connection
}
catch (Exception e1)
{
}
}
A using statement is translated into three parts: acquisition, usage, and disposal.
using (OleDbConnection conn = new OleDbConnection(conString))
{
conn.Open();
return (conn.State == ConnectionState.Open);
//connection is automatically closed and disposed here
}
More information at MSDN article.
You better give back an open connection because you need that in an OleDbCommand. You coukd hide the connection as well in the Common class if you like but if you keep it in the using statement there is no open connection when you get status so basically if true is returned your connection in reality is closed (and Disposed). Refactor to something like this:
public OleDbConnection GetOpenConnection()
{
string conString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|db_gym.mdb; Jet OLEDB:Database Password=gym_admin";
OleDbConnection conn = new OleDbConnection(conString))
conn.Open();
return conn;
}
protected void btn_general_Click(object sender, EventArgs e)
{
try
{
using(OleDbConnection openConnection = common.GetOpenConnection())
{
// I want to close this connection
openConnection.Close(); // close asap
} // dispose
}
catch (Exception e1)
{
}
}

Categories