I have my connection string stored in App.Config
<connectionStrings>
<clear />
<add name="CTaC_Information_System.Properties.Settings.CIS_beConn"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source="\\server\file\CIS Data\Database\CIS_be.accdb"e;;Jet OLEDB:Database Password=123"
providerName="System.Data.OleDb" />
Then when I go to my main.xaml.cs I type in the following:
string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;`
I found that answer on Stack Overflow when searching, but some were say to put var but when I typed var it wouldn't recognize it so I went with the string method.
When I go to type cisconn.Open(); the option isn't there. I am referencing System.Configuartion;,System.Data.Sql; System.Data.SqlClient; and System.Data.OleDb;.
Can someone show / tell me how I can connect to the database from c#? I'm trying to test the connection when my application runs but I can't figure it out.
The connection string is just a string, its meant to be used in your connection, so you should do:
public void DoSomeDatabaseOp()
{
string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(cisconn))
{
conn.Open();
//Create your commands or do your SQL here.
}
}
You should create/destroy the connection inside the method you are using it in. Don't keep a reference to it in the root of the class object. This keeps the connections clean and open if you aren't doing database operations.
If you really wanted to though, you could do this:
class MyClass
{
OleDbConnection _rootConn;
string _connStr;
public MyClass()
{
_connStr = string cisconn = ConfigurationManager.ConnectionStrings["CTaC_Information_System.Properties.Settings.CIS_beConn"].ConnectionString;
_rootConn = new OleDbConnection(_connStr);
}
public void DoSomeDatabaseOp()
{
//Use _rootConn here
}
}
BUT the class should implement IDisposable so that it can dispose of the connection properly! How to implement IDisposable is beyond the scope of the answer, but look up how to implement it properly.
Related
I have a WinForm application developed on one laptop connected to an SQL server on the same laptop.
I have a new laptop and have created a docker setup for an SQL server. I am looking to change the code base to use the new SQL server.
The new server is using SQL Server auth with username and password on the new laptop. The old laptop is using windows authentication on a windows installed setup. I have migrated a copy of the entire DB into my dockerised instance of the sql server.
The application has the connection settings in the app config and naturally this is for windows authentication.
My app.config is comitted to my github repository. I do not want to store the sql user/password in the app.settings, but instead I would like to get these from env variables I set on the machine.
I would also like to know how to change the format of the connection string in app.config so it works with sql server authentication.
Or maybe now I have explained what I am trying to do, there might be a better way?
My current connection strings are
<connectionStrings>
<add name="Blah.Properties.Settings.BlahConnectionString"
connectionString="Data Source=W.....R....;
Initial Catalog=Blah;
Integrated Security=True;
Connect Timeout=30;Encrypt=False;
TrustServerCertificate=False"
providerName="System.Data.SqlClient"/>
</connectionStrings>
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="Blah")]
public partial class BlahDBDataContext : System.Data.Linq.DataContext
I searched all code for 'AddDbContextFactory' and 'GetConnectionString'
public BlahDBDataContext() :
base(global::Blah.Properties.Settings.Default.BlahConnectionString, mappingSource)
{
OnCreated();
}
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=PCNAME;Initial Catalog=Blah;Integrated Security=True" + ";Connect Timeout=30;Encrypt=False;TrustServerCertificate=False")]
public string BlahConnectionString
{
get { return ((string)(this["BlahConnectionString"]));
}
The database context class is generated code inheriting as far as I can tell on System.Data.Linq.DataContext, as shown by this code from my application.
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="Blah")]
public partial class BlahDBDataContext : System.Data.Linq.DataContext
{
The BlahDBDataContext class provides a number of constructors. Please check for yourself for a fuller list.
For my purposes the constructor I needed was
public BlahDBDataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
This requires the construction of a System.Data.IDbConnection object to hold/manage the connection details.
Therefore in my case all I needed to do was construct the connection string, for example.
string userName = EnvironmentVariables.GetValue("BLAH_USERNAME");
string password = EnvironmentVariables.GetValue("BLAH_PASSWORD");
string server = EnvironmentVariables.GetValue("BLAH_SERVER");
string database = EnvironmentVariables.GetValue("BLAH_DATABASE");
connectionString = $#"Data Source={server};Initial Catalog={database};Integrated Security=False;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;User ID={userName};Password={password};";
and then all thats needed is
new BlahDBDataContext(
new SqlConnection(
Program.GetDatabaseConnectionString()))
Where Program.GetDatabaseConnectionString() is.
public static string GetDatabaseConnectionString()
{
if (connectionString is null)
{
string userName = EnvironmentVariables.GetValue("BLAH_USERNAME");
string password = EnvironmentVariables.GetValue("BLAH_PASSWORD");
string server = EnvironmentVariables.GetValue("BLAH_SERVER");
string database = EnvironmentVariables.GetValue("BLAH_DATABASE");
connectionString = $#"Data Source={server};Initial Catalog={database};Integrated Security=False;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;User ID={userName};Password={password};";
}
return connectionString;
}
From a SOLID principles and clean coding perspective this is requires refactoring, and will be cleaned up now I have working code.
This is a noob question but I have been stuck here for a few hours so I need to get passed this. I have this Windows App that performs a simple function. It makes a trip to the DB and checks if a specific record exists and if it does then perform some operation. However it just doesn't want to read the connection string - it comes as null all the time. I keep getting null every time I initialize my connection string. What could I be doing wrong. I only have one connection string named App.config.
Class File:
private class ClassA
{
private string myConnectionString = "";
private SqlConnection mySQLConnection;
private SqlCommand mySQLCommand;
private int CheckIfSerialNumberExists(UInt64 ColumnToCheck)
{
int countResult = 0;
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString; //I get an object reference null here when the compiler executes this line. I have been using this structure for years and never got any issues
using (mySQLConnection = new SqlConnection(myConnectionString))
{
string procName = "SELECT Count(*) ColumnName FROM Table WHERE ColumnName='" + ColumnToCheck + "'";
mySQLCommand = new SqlCommand(procName, mySQLConnection);
mySQLConnection.Open();
countResult = (int)mySQLCommand.ExecuteScalar();
}
return countResult;
}
private void someFunc()
{
//Test value: 5
if(CheckIfSerialNumberExists(5) > 0)
{
//Don't do anything
}
else
{
//Save to DB
}
}
}
Config File:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="ConnectionStringName"
connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=**;Password=****"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/></startup>
</configuration>
So here is the quick fix:
In my windows app I am referencing a class library project. I had only added the connection string in that project. I added it to my windows app project and there we go, all was working. Really feel like an idiot.
I know work with db.So i in my class have static object:
static private MySqlConnection conn = null;
public static Boolean postoji(String username, String password)
{
conn = new MySqlConnection("Server=127.0.0.1;Database=cs322;Uid=root;Password =; ");
Boolean rez=false;
try
{
conn.Open();...
In this class i have 5 mehtods,so i thinking,does is better to have this static object null,and initialization them in every method.Or have static object which is alrady created.
private MySqlConnection conn== new MySqlConnection("Server=127.0.0.1;Database=cs322;Uid=root;Password =; ");
and methods just use them.
I would say better would be have this connection string in your web.config or app.config and read it from there instead of defining your connection string in code. So that in future if your connection string needs change you know only one place change would present as well editing config file doesn't need you to re-publish your code.
You should be putting all the connection string in the configuration file. Below is the code sample for putting and reading it from confile fie.
web config file
<add name="ConnectionStringName" connectionString=127.0.0.1"; Initial Catalog=cs322; Integrated Security=True"/>
Also same time i would suggest to wrap your connection within the Using block like below example.
Reading code from code behind
using(MySqlConnetion connection = new MySqlConnetion(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString()))
{
connection.open();
//setup and execute query
} //connection gets closed here
Here, once you exit the using block, the connection is closed.
I'm a 17 year old software engineering student and am having trouble with linking my sql database to my C# Win App. I was able to accomplish this task using a access database but the database needs to be in SQL. Any Help would be greatly appreciated!
The code i have so far is :
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb; // all Non-SqlServer Databases ie oracle, access, sqlLite
using System.Configuration;
namespace SqlWinApp
{
public partial class Form1 : Form
{
// Declare and init data objects
// Connect to an external data source
//OleDbConnection cnDataCon =
// new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=H:/SEWD/ASP/dataTestJr/App_Data/dbWaxStax.accdb");
SqlConnection cnDataCon =
new SqlConnection(ConfigurationManager.ConnectionStrings["cnExternalData"].ConnectionString);
// dataset: Container object for data tables
DataSet dsData = new DataSet();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
cnDataCon.Open();
{
loadDdlTitles();
}
}
catch (Exception errDesc)
{
string strMsgError = "Error encountered on open: " + errDesc.Message.ToString().Replace('\'', ' ');
MessageBox.Show(#"<script language='javascript'>alert('" + strMsgError + "')</script>");
MessageBox.Show(#"<script language='javascript'>alert('Application will terminate')</script>");
return;
}
}
private void loadDdlTitles()
{
//Response.Write(#"<script language='javascript'>alert('loadDDlTitles')</script>");
// store sql into a string in order to be utilized at a later time.
string strSqlTitles = "SELECT * FROM tblTitles ORDER BY title";
// data adapters act as data filters
OleDbDataAdapter daTitles = new OleDbDataAdapter();
// command syncs the data source with the filter (data sdapter) and readies it for instantiation
OleDbCommand cmNameTitles = new OleDbCommand(strSqlTitles, cnDataCon);
// select command syncs the filter with the data
daTitles.SelectCommand = cmNameTitles;
try
{
daTitles.Fill(dsData, "tblTitlesInternal"); // blow pt.
}
catch (Exception errDesc)
{
string strMsgError = "Error encountered in data adapter object: " + errDesc.Message.ToString().Replace('\'', ' ');
MessageBox.Show(#"<script language='javascript'>alert('" + strMsgError + "')</script>");
MessageBox.Show(#"<script language='javascript'>alert('Application will terminate')</script>");
}
// Connect control obj to datasource and populate
ddlTitle.DataSource = dsData.Tables["tblTitlesInternal"];
ddlTitle.DisplayMember = "nameTitle";
ddlTitle.ValueMember = "nameTitlesID";
}
}
}
In my App.config i have:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="cnExternalData" connectionString="Data Source=|DataDirectory|215-6576.All-Purpose Handyman.dbo; Provider=Microsoft.ACE.OLEDB.12.0" />
<add name="SqlWinApp.Properties.Settings.ConnectionString" connectionString="Data Source=215-6576;User ID=sa"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Finally, My database is named 215-6576.All-PurposeHandyman.dbo and the table i am using is named tblTitles. Any help again would be greatly appreciated! Thank you!
An invaluable website I've gone to repeatedly is ConnectionStrings.com.
Assuming everything you already have is correct, you just need to modify your SQL connection string in the config file:
<add name="SqlWinApp.Properties.Settings.ConnectionString" connectionString="Server=215-6576;User ID=sa; Database=All-PurposeHandyman; Password=password"
providerName="System.Data.SqlClient" />
If your sa account has a password, you will need to provide that as well via "Password=[Password]" in that same connectionString attribute.
EDIT
In your C# code, you don't need the braces around your call to loadDdlTitles();, you can safely remove those.
EDIT2
Added password attribute into modified connection string to make clear how it should work.
Well, I see 3 problems just off the bat (and there might be more if I looked more closely). The two that are causing you trouble are:
You're still calling your Access connection string
Your SQL connection string is formatted incorrectly.
The third problem isn't major, but it'll be annoying when you go to fix #1: your connection string name is really long.
Modify your sql connection string thusly:
<add name = "SqlConnection" connectionString="[yourConnectionStringHere]" />
Then modify your calling code:
SqlConnection cnDataCon =
new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString);
For the specific connection string, I recommend heading to http://connectionstrings.com and taking a look. But it will be something like this:
Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword;
You need to have the server/machine name in the connection string. This link has some information and examples to use:
http://msdn.microsoft.com/en-us/library/jj653752%28v=vs.110%29.aspx
If I'm letting Visual Studio take care of adding an SQL Server database to an existing project, it adds the connection string to app.config. How can I use use THAT connection string to make my own connections and datasets?
Use the ConfigurationManager.AppSettings to read the connection string when required.
For example, if you opening a SQL Connection, use the assign the "Connection String" property to the value retrieved from ConfigurationManager.AppSettings ("MyConnectionString")
If it is placed in the appropriate section in the app config file, then you can use ConfigurationManager.ConnectionStrings to retrieve it as well.
Read more here http://msdn.microsoft.com/en-us/library/ms254494.aspx
Place the connection string in your app.config then use
ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
to get the connection string.
For example:
private string GetConnectionString(string str)
{
//variable to hold our return value
string conn = string.Empty;
//check if a value was provided
if (!string.IsNullOrEmpty(str))
{
//name provided so search for that connection
conn = ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
}
else
//name not provided, get the 'default' connection
{
conn = ConfigurationManager.ConnectionStrings[ConnStr].ConnectionString;
}
//return the value
return conn;
}
Then you can reference the connection using ado.net or Linq
For Example:
your app.config would contain an entry like:
<connectionStrings>
<add name="nameofConnString" connectionString="Data Source=SQLDATA;Initial Catalog="nameofdatabase";Persist Security Info=True;User ID=username;Password=password;Connection Timeout=30;Pooling=True; Max Pool Size=200" providerName="System.Data.SqlClient"/>
'
Then you could call
conStr = GetConnectionString("nameofConnString")
With Ado.net
You could then establish the connection with:
sqlConn = new SqlConnection(conStr);
sqlConn.Open();
Or with Linq
LinqData ld = new LinqData();
DataContext dataContext = new DataContext(ld.GetConnectionString(sqlConn));
where LinqData is a class that contains the GetConnectionString() method.
Well, both of those helped get me on the right track. I found this quite simple, yet highly annoying. The solution I used was:
using System.Configuration;
add a reference System.configuration
create a new connection with SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabaseConnectionFromApp.Config"].ConnectionString)