SQL Server Database Connection C# ASP.NET - c#

To initialize the connection string, it needs to be a static string. Why that happens?
using System.Data.SqlClient;
namespace CDemoLib
{
public class Connecting
{
static string conString = #"connection string here";
Also when I am trying to open a connection using the conn.Open()am getting an error saying that
The name conn.Open() does not exist in the current context
Why that error occurs ?
using System.Data.SqlClient;
namespace CDemoLib
{
public class Connecting
{
static string conString = #"connection string here";
SqlConnection conn = new SqlConnection(conString);
conn.Open();

I have anwsered this question but i will replay it for you.
(Connection String Is not Working Object instance reference is null)
Put your connection string at you web.config as the foloow example:
<add name="MovieDB"
connectionString="Data Source=LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet- MvcMovie;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Movies.mdf"
providerName="System.Data.SqlClient"/>
to read it within your code:
System.Configuration.Configuration rootWebConfig =System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["MovieDB"];
if (connString != null)
Console.WriteLine("MovieDB connection string = \"{0}\"",
connString.ConnectionString);
else
Console.WriteLine("No MovieDB connection string");
}
The name at your web.config tag 'name'
<add name="MovieDB".....
has to be the same one from your c# code:
connString = rootWebConfig.ConnectionStrings.ConnectionStrings["MovieDB"]
from: https://msdn.microsoft.com/en-us/library/ms178411.aspx
Here a method to open it:
private static void OpenSqlConnection(string connString)
{
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}
from: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx
DonĀ“t forget to secure your connection string at your web.config. Please, read this: https://msdn.microsoft.com/en-us/library/ms178372.aspx

Related

Asp.net MVC SQL Server connection return null

I am trying to connect to Microsoft SQL Server on localhost. My code is as follows.
public SqlConnection con;
// To Handle connection related activities
private void connection()
{
string constr = ConfigurationManager.ConnectionStrings["Data Source = MACHINE-VOIV7EH\\SQLEXPRESS; Initial Catalog = geolog; Persist Security Info = False; "].ToString();
con = new SqlConnection(constr);
}
public List<Bob> GetAllBobs()
{
try
{
connection();
con.Open();
IList<Bob> EmpList = SqlMapper.Query<Bob>(con, "GetBobs").ToList();
con.Close();
return EmpList.ToList();
}
catch (Exception)
{
throw;
}
}
con return null
SQL Server settings:
Configuration from Pyton (try, but another database):
conn = pypyodbc.connect('DRIVER={SQL Server};'
r'SERVER=MACHINE-VOIV7EH\SQLEXPRESS;'
r'DATABASE=vibori;'
r' autocommit=True'
)
The Problem is with your connection string. You should reference your connection string from the web.config file.
Web.Config
<connectionStrings>
<add name="master" providerName="System.Data.SqlClient" connectionString="Data Source=ACHINE-VOIV7EH\\SQLEXPRESS;Initial Catalog=geolog;Integrated Security=False;User Id=your_user_id;Password=xxxxxx;MultipleActiveResultSets=True" />
</connectionStrings>
C# File
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["master"].ConnectionString);
Or you can just send a connection string as follows
private void connection()
{
string constr = "Data Source=MACHINE-VOIV7EH\\SQLEXPRESS; Initial Catalog = geolog; Persist Security Info = False;";
con = new SqlConnection(constr);
}
The string index of ConfigurationManager.ConnectionStrings[string] is the connection name, not the connection string which is what it returns. Use your web configuration file (web.config) to add one or more named connection strings which can be returned by this indexer.
Example:
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString
and partial web.config content
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=MACHINE-VOIV7EH\SQLEXPRESS;Initial Catalog=vibori" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>

C# method returns connect to different databases

UPD:
I have a static class for work with database.
This class contains the method which returns connect to database. Early this method returns connect to Advantage database (AdsConnection):
static private AdsConnection GetConnection(){
var conn = new AdsConnection();
conn.ConnectionString = here my connection string
return conn;
}
Now, I need to change this method. I need that this method returns connect to different databases types (Advantage database, Oracle database).
The method will work into public methods in my class. For example, method for get data from any table from database.
public static List<entity1> GetEntities(){}
Into this method the first of my step is to resolve the type of database, then connect to database. Then get data from database and the last step is return data (List< entity1 >).
In the step to connect the database I need to use the method GetConnection("Ads")
This method returns current connect to database and then I can use this connect for work
I changed method:
My first version
static private T GetConnection<T>(string dbType)
{
if (dbType.Equals("Oracle"))
{
OdbcConnection conn = new OdbcConnection
conn.ConnectionString = here my connection string
return (T)conn;
}
if (dbType.Equals("Ads"))
{
AdsConnection conn = new AdsConnection
conn.ConnectionString = here my connection string
return (T)conn;
}
return default(T);
}
But, my solution does not work. I have errors:
Cannot convert type 'System.Data.Odbc.OdbcConnection' to 'T'
Cannot convert type 'Advantage.Data.Provider.AdsConnection' to 'T'
I do not know how to resolve my problem.
Please, tell me how to resolve my problem?
Now, I use the following code (this solution give me #khlr):
static private IDbConnection GetConnection(string dbType)
{
if (dbType.Equals("Oracle"))
{
OdbcConnection conn = new OdbcConnection
conn.ConnectionString = here my connection string
return conn;
}
if (dbType.Equals("Ads"))
{
AdsConnection conn = new AdsConnection
conn.ConnectionString = here my connection string
return conn;
}
return null;
}
Thank.
One way you can abstract the connection instantiation is by using DbProviderFactory of ADO.Net. You can basically pass it a provider name and it will give a connection based on the provider. This basically reduce the check of dbtype etc for you and I think its sensible approach when you need to target multiple database. Some of the code snippet are copied from MSDN.
In you config file you can multiple connection string set up with different database type and provider.
<configuration>
<add name="NorthwindAccess"
providerName="System.Data.OleDb"
connectionString=
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Northwind.mdb;"
/>
Then in you method you can do following:
static DbConnection CreateDbConnection(
string providerName, string connectionString)
{
// Assume failure.
DbConnection connection = null;
// Create the DbProviderFactory and DbConnection.
if (connectionString != null)
{
try
{
DbProviderFactory factory =
DbProviderFactories.GetFactory(providerName);
connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
}
catch (Exception ex)
{
// Set the connection to null if it was created.
if (connection != null)
{
connection = null;
}
Console.WriteLine(ex.Message);
}
}
// Return the connection.
return connection;
}
You could do the following, since both connections inherit from IDbConnection:
static private IDbConnection GetConnection(string dbType)
{
if (dbType.Equals("Oracle"))
{
OdbcConnection conn = new OdbcConnection
conn.ConnectionString = here my connection string
return conn;
}
if (dbType.Equals("Ads"))
{
AdsConnection conn = new AdsConnection
conn.ConnectionString = here my connection string
return conn;
}
return null;
}

Why I am receiving an Object reference not set error

My C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Configuration;
public partial class zzsearch : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PopulatePhysician();
}
public void PopulatePhysician()
{
string myQuery = "SELECT * FROM tblPhysician";
string conn = ConfigurationManager.ConnectionStrings["ConnStringTEST"].ConnectionString;
SqlConnection cn = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand(myQuery, cn);
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
if (!IsPostBack)
{
name.DataSource = ddlValues;
name.DataValueField = "content_id";
name.DataTextField = "content_title";
name.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Last Name...";
Item.Value = "0";
//Item.Selected = True
name.Items.Insert(0, Item);
}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
}
My partial web.config file:
<appSettings file="Application.config">
<add key="ConnStringTEST" value="Data Source=ep-db;Initial Catalog=DSCONTENT;Integrated Security=FALSE;user=zytuid;pwd=testingitout;" />
</appSettings>
ASP code:
<asp:DropDownList ID="name" runat="server" ClientIDMode="Static">
</asp:DropDownList>
Why do I receive the following error:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 21: {
Line 22: string myQuery = "SELECT * FROM tblPhysician";
Line 23: string conn = ConfigurationManager.ConnectionStrings["ConnStringTEST"].ConnectionString;
Line 24: SqlConnection cn = new SqlConnection(conn);
Line 25: SqlCommand cmd = new SqlCommand(myQuery, cn);
Source File: c:\Webserver\WWESTEXEC\zzsearch.aspx.cs Line: 23
Because ConfigurationManager.ConnectionStrings["ConnStringTEST"] is returning null.
ConnectionStrings does not reference the appSettings section. It references the connectionStrings section.
The problem is that the connection string is added as an AppSettings entry, not as a connection string in your config file. That's why ConfigurationManager.ConnectionStrings["ConnStringTEST"] returns null and the call to the ConnectionString property results in a NullReferenceException.
Change this
<appSettings file="Application.config">
<add key="ConnStringTEST" value="Data Source=ep-db;Initial Catalog=DSCONTENT;Integrated Security=FALSE;user=zytuid;pwd=testingitout;" />
</appSettings>
To this;
<connectionStrings>
<add name="ConnStringTEST" connectionString="Data Source=ep-db;Initial Catalog=DSCONTENT;Integrated Security=FALSE;user=zytuid;pwd=testingitout;" />
</connectionStrings>
For detailed information on how to configure and retrieve connection strings in ADO.NET, see this link.
You should check if the value is set before you can call ConnectionString .
Replace your code with the following:
string conn = ConfigurationManager.ConnectionStrings["ConnStringTEST"].ConnectionString
to
if(!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings["ConnStringTEST"])){
string conn = ConfigurationManager.ConnectionStrings["ConnStringTEST"].ConnectionString ;
}
I think your issue is that you are looking in ConfigurationManager.ConnectionStrings and not ConfigurationManager.AppSettings. What i mean is that your connection string in your web config is in the AppSettings section and not in the connectionStrings section.
Try This:
string conn = ConfigurationManager.AppSettings["ConnStringTEST"];

cannot connect to oracle server from C#.net application

I'm trying to connect to remote Oracle server. My connection string -
OdbcConnection con = new OdbcConnection();
con.ConnectionString = #"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= xxxx)(PORT=xxxxx))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=abc.domain.com)));USER ID=user1;Password=pwd;";
I encountered error saying - "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified" (System.Data.Odbc.OdbcException) Exception Message = "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified", Exception Type = "System.Data.Odbc.OdbcException", Exception WinRT Data = ""
I specified my connection string according to my TNSNAMES.ora
Entry for my DB in TNSNAMES.ora goes like this:
DB.WORLD=
(DESCRIPTION=
(ADDRESS=
(PROTOCOL=TCP)
(HOST= xxxx)
(PORT=xxxxx)
)
(CONNECT_DATA=
(SERVER=dedicated)
(SERVICE_NAME=abc.domain.com)
)
)
Can someone explain on the error. Please help/suggest if my connection string went wrong and how to connect to Oracle server from my windows application
first install odp.net.managed using nuget packet manager:
Install-Package odp.net.managed
odp.net.managed work without preinstalled Oracle Client
next:
const string connectionString = #"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= xxxx)(PORT=xxxxx))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=abc.domain.com)));USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
if you have tnsnames.ora in application folder:
const string connectionString = #"Data Source=DB.WORLD;USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
or if tnsnames.ora in other folder:
Environment.SetEnvironmentVariable("TNS_ADMIN", #"path_to_tnsadmin.ora");
const string connectionString = #"Data Source=DB.WORLD;USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
you need to use OracleConnection
OracleConnection conn = new OracleConnection(connectionString);
download and install Oracle Data Provider for .NET
Go to Connections Strings for Oracle
Maybe will find some help
Use following Code:
using System;
using Oracle.DataAccess.Client;
class ConnectionSample
{
static void Main()
{
OracleConnection con = new OracleConnection();
//using connection string attributes to connect to Oracle Database
con.ConnectionString = "User Id=scott;Password=tiger;Data Source=oracle";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
// Close and Dispose OracleConnection object
con.Close();
con.Dispose();
Console.WriteLine("Disconnected");
}
}
Source ONE , TWO and THREE
Try something like this class :
public class OracleOperations
{
OracleConnection oraConn = new OracleConnection();
private bool connStatus;
public OracleOperations()
{
connStatus = false;
connect();
}
~OracleOperations()
{
disconnect();
}
public bool getConnStatus()
{
return connStatus;
}
public void connect()
{
string connString = "User Id=xxxx; Password=yyyyy; Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.10.10.10)(PORT=1583))(CONNECT_DATA=(SERVER=dedicated)(SID=oracledb)))";
if (oraConn.State != ConnectionState.Open)
{
try
{
oraConn.ConnectionString = connString;
oraConn.Open();
Console.WriteLine("Successful Connection");
connStatus = true;
}
catch (Exception eOra)
{
Console.WriteLine(eOra.Message+ "Exception Caught");
connStatus = false;
throw eOra;
}
}
}
public void disconnect()
{
if (oraConn.State == ConnectionState.Open)
{
try
{
oraConn.Close();
connStatus = false;
Console.WriteLine("Connection Closed");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "Exception Caught");
}
}
}
}
I would try Tnsping utility to make sure you can connect via tnsnames.ora
Try putting tnsnames.ora and sqlnet.ora in the same folder of the application and see if that addresses the issue.
With Managed ODP.Net there is one catch it does not support LDAP look up (e.g. LDAP.ora)
I'Ve Created an app.config File and configured the DB entry like this
<configuration>
<configSections>
<section name ="Environment" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<Environment>
<add key ="CIT" value ="Password=pwd123;User ID=abc123;Data Source=db1;Persist Security Info=True;Provider=MSDAORA"/>
<add key ="SIT" value ="Password=pwd234;User ID=abc234;Data Source=db2;Persist Security Info=True;Provider=MSDAORA"/>
<add key ="UAT" value ="Password=pwd345;User ID=abc345;Data Source=db3;Persist Security Info=True;Provider=MSDAORA"/>
</Environment>
</configuration>
Reffered that configuration into my form using ConfigurationManager(Need to refer the assembly - system.configuration). Add namespace - using System.Collections.Specialized to avail NameValueCollection. Code goes like this
environments = ConfigurationManager.GetSection("Environment") as NameValueCollection;
string strConnString = environments[envs];
conn = new OleDbConnection(strConnString);
conn.Open();
OleDbDataAdapter objDa = new OleDbDataAdapter("select * from tblABC", conn);
DataSet ds1 = new DataSet();
objDa.Fill(ds1); dataGridView1.DataSource = ds1.Tables[0];
Using datset, i've populated datagrid using an OleDbDataAdapter. It worked for my Windowsapplication.

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

Categories