connection.open hanging/freezing. What is wrong with my connection string? - c#

I wanted to make my connection string dynamic so I don't have to recompile my code for each new user.
my old connection string:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\Storm\documents\visual studio 2015\Projects\SeaSideBlissVersion2\SeaSideBlissVersion2\ShopDb.mdf";Integrated Security=True
My config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="ConnString"
connectionString="Data Source=.;Initial Catalog=ShopDB;Integrated Security=True"/>
</connectionStrings>
</configuration>
and then some code in my db class:
class DB
{
static string conn;
static SqlConnection _conn;
public DB()
{
conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
_conn = new SqlConnection(conn);
}
public void dbAddItem(string name, string measurement, string PLU)
{
string query = string.Format("INSERET INTO tblItems (ItemName, Measurement, Stock, PLUNumber) VALUES ({0}, {1}, {2}, {3})", name, measurement, 0, PLU);
_conn.Open();
SqlCommand comm = new SqlCommand(query, _conn);
comm.ExecuteNonQuery();
_conn.Close();
}
}
And used the following references:
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
When I call my dbAddItem method it seems to hang at _conn.Open()
I'm assuming there's something wrong with my connection string? I've looked it up and nothing that I found helped.

Seems The mistake was obvious, once I put my .mdf db into the debug folder it worked. It makes sense because there is no "exact" directory to look in.

It seems that you missed login info to the DB in the connection string.
Something like "uid=xxx;pwd=xxx".

Related

Connection string reference not set to an instance of an object

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.

Cannot access connection string in app.config by using c#

App.config file configuration 1
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=223.29.207.133;
Initial Catalog=MBV5DBLive;User ID=smsuser;Password=sms;IntegratedSecurity=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
App.config file configuration 2
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=localhost;
Initial Catalog=University;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
C# code
try
{
String constring = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
}
}
catch (Exception ex)
even if i debug when it comes to configuration manager code will jump to catch block and it will show "Object reference not set to an instance of an object."
What is the issue with above both configuration files?
Your connection string name seems like c_str not MyDBConnectionString.
And since you don't have any MyDBConnectionString in your web config, your ConfigurationManager.ConnectionStrings["MyDBConnectionString"] returns null and that's why you get NullReferenceException when you try to access ConnectionString property of a null reference.
If everything is okey other than that, this should work;
var constring = ConfigurationManager.ConnectionStrings["c_str"].ConnectionString;
using (var con = new SqlConnection(constring))
{
}

Using a connection string in a app.config file in a .cs file

I've got a connection string to my database in a my app.config file. I want to using the app.config file rather than copying and pasting the string in the section i want to use it is.
My app.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="|DataDirectory|\SVN .mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and my .cs file is currently like this:
private void sendToDB_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("user id=username;" +"password=password;server=serverurl;" + "Trusted_Connection=yes;" + "database=database; " + "connection timeout=30");
}
I know that this is wrong but want to use the config file instead.
Can anyone help me in how I would go about doing this.
var connectionString=ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
Note : try to keep the name of the connectionstring simpler for readability purposes.
Also,Your assembly also needs a reference to System.Configuration.dll
If you want to access the ConnectionStrings property of your application-configuration file, you have to ...
add a reference to the System.Configuration-dll.
add this to the top of the file:
using System.Configuration;
Then you can access it in this way:
string conStr = ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
using(var con = new SqlConnection(conStr))
{
// ...
}

C# Sql Connection String

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

Accessing database connection string using app.config in C# winform

I can't seem to be able to access the app.config database connection string in my c# winforms app.
app.config code
<connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
C# code:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["MyDBConnectionString"];
When I try the C# code, I get a message:
Warning 1 'System.Configuration.ConfigurationSettings.AppSettings' is obsolete: '
This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings'
However, when I try to use:
conn.ConnectionString = System.Configuration!System.Configuration.ConfigurationManager.AppSettings["MyDBConnectionString"];
I get an error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
This is all you need:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
Use ConfigurationManager instead of ConfigurationSettings. It has a ConnectionStrings property that you should use for connection strings in the connectionStrings section:
ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
You are using the ConnectionStrings collection, not the AppSettings.
ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=MY-PC;Initial Catalog=DB2013;User ID=sa;Password=MYSQL123" />
</appSettings>
</configuration>
using System.Configuration;
using System.Data.SqlClient;
namespace OnlineDelete_W2013
{
public partial class CommodityEdit : Form
{
SqlConnection MyConnection = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
public CommodityEdit()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
MyConnection.Open();
}
catch (Exception)
{
throw;
}
}
}
}
try this
ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnection"].ToString()))
{
....(your code here) ...
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["MyDBConnectionString"].ConnectionString;
try
{
conn.Open();
}
catch (Exception)
{
throw;
}
The answers stating to use the line
ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
are correct.
If an error appears stating that ConfigurationManager does not exist, it's because your project hasn't referenced System.Configuration.
To do that in .NET Framework, in Solution Explorer, in the project where you want to use this line of code, right-click in References, choose Add Reference..., then choose Assemblies on the left-side and Framework under it. Pick System.Configuration on the list and click Ok.
About this:
I get an error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
I just declared a var like this and solved the problem:
var strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
Please try below code. this is as you are expecting:
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

Categories