C# Sql Connection String - c#

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

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.

Error populating dropdownlist from SQL Database

So I have successfully add a data connection to my VS project and now I'm trying to populate the drop down menu that I created with the data from the tables coming from the database; however, when I run the code it says, "Login failed for use 'Username', on this line:
cmd.Connection.Open();
This is my C# code:
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace Test1234
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateDDList1();
//PopulateDDList2();
//PopulateDDList2_1();
}
public void PopulateDDList1()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM [History]", new SqlConnection(ConfigurationManager.AppSettings["Connection"]));
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
DropDownList1.DataSource = ddlValues;
DropDownList1.DataValueField = "Serial";
DropDownList1.DataTextField = "Serial";
DropDownList1.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}//end Populate 1
}
}
This is the web.config code:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="ActioNetITInventoryConnectionString" connectionString="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=ActioNet1234"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="Connection" value="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=***********;Integrated Security=True"/>
</appSettings>
</configuration>
<appSettings>
<add key="Connection" value="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=***********;Integrated Security=True"/>
</appSettings>
Your connection string contains both a login & password as well as Integrated Security=True
If you are trying to log on with a named login/password, then either set Integrated Security=False or leave it out altogether
I think there error occures due to your connection string. Is there a reason that you don't use the servername but its IP?
By the way: You defined it twice in two different config sections..
If you're using the IP, then you have to add the port:
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;
Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;
Alternatively you could use the standard way:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Or even better if possible: Use trusted connection:
Server=myServerAddress;Database=myDataBase;
Generally have a look here: http://www.connectionstrings.com/sql-server/
You have several potential failure points, for instance:
Calling ExecuteReader but not actually validating data, ie no Null.
Potentially several Columns being returned, when you only need a Key and Value.
Are you sure Serial is valid Column.
Your connection includes integrated security and a login / password. Use one or the other. (Kritner's answer has good information and direction for this).
To make your code a bit more legible and robust, you could do the following:
public IList<TModel> GetModel<T>(string query) where TModel : new()
{
var container = new List<T>();
using(var connection = new SqlConnection(dbConnection))
using(var command = new SqlCommand(query, connection))
{
connection.Open();
using(var reader = command.ExecuteReader())
while(reader.Read())
{
TModel model = new TModel();
var type = model.GetType();
var table = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();
foreach(var property in type.GetProperties())
foreach(var column in table)
if(String.Compare(property.Name, column, true) == 0)
if(!reader.IsDBNull(reader.GetOrdinal(property.Name)))
property.SetValue(model, reader.GetValue(reader.GetOrdinal(property.Name)), null);
container.Add(model);
}
}
}
The following method will build your model, so you would simply do:
drpExample.DataSource = GetModel<Person>("SELECT * FROM [History]");
drpExample.DataBind();
You really shouldn't have a direct query like that, you should really use Parameters but this should get you started. Also you will need the DataKeyValue and DataKeyText which I often apply to the front-end. You would simply set the value to the correlated Property in your model.
As stated in my comment, you can't provide both login credentials and state integrated security=true - it's one or the other.
Integrated Security basically says "use the current domain credentials I'm logged into the system with."
That being said, you probably want it to look like this:
<add key="Connection"
value="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=ActioNet1234;"/>
Although the "Connection" seems redundant as you already have a connection string with the same information. You can use that like this:
SqlCommand cmd = new SqlCommand(
"SELECT * FROM [History]",
new SqlConnection(
ConfigurationManager.ConnectionStrings["ActioNetITInventoryConnectionString"].ConnectionString)
)
);

Connecting to connectionString in app.config

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&quote;;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.

binding datagrid for Wpf to a DB

I am trying bind a DataGrid for WPF to a table in MS SQL Database.
1) First I created a App.config file as followsrrr
<connectionStrings>
<add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress;
User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
<connectionStrings/>
2) Secondly, I added a datagrid to my Form with a name grdEventLog
<Grid>
<DataGrid Name="grdEventLog"/>
</Grid>
3) then I added this code to MainWindow.xaml.cs file as follows:
using System.Data;
using System.Data.SqlClient;
using System.Web;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
FillDataGrid();
}
private void FillDataGrid()
{
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string CmdString = string.Empty;
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT Server,Date,Typ,Msg FROM EventLog";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("EventLog");
sda.Fill(dt);
grdEventLog.ItemsSource = dt.DefaultView;
}
}
After typing all these entries, I have the error at ConfigurationManager stating "The name does not exist in the current context"
I am trying to add reference cfgmgr32.dll to overcome this error. But it is not being accepted. Can anyone suggest to over come this error ?!
Alternative suggestion for approaching databinding in WPF is also welcome.
The problem is not in databinding itself. Seems, there is a typo either in config file, or in key used in ConnectionStrings[]. It would be useful if you post entire error with stacktrace here.
P.S. There is a typo in your config file.
It should be not
<connectionStrings>
<add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress;
User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
<connectionStrings/>
but
<connectionStrings>
<add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress;
User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
</connectionStrings>
See the last line.

linq - inserting new data replaces existing data on database.why?

When I call the datacontextInstance.Insertonsubmit() and datacontextinstance.submitChanges(), it clears all the existing data in the database before inserting the new data.
How do I perform a real insert operation?
I want to add new data to the existing table without clearing out the existing data.
Thanks
Edit:
Here's my test code which i tried...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DataClasses1DataContext entities = new DataClasses1DataContext();
for (int i = 1; i <= 100; i++)
{
textdata dt = new textdata();
dt.id = i;
dt.ipaddress = "172.168.3.2";
dt.pcname = "testusr";
dt.publicip = "test pub ip";
dt.username = "testusr";
dt.textdata1 = "Some DATA";
dt.dttime = DateTime.Now;
entities.textdatas.InsertOnSubmit(dt);
entities.SubmitChanges(System.Data.Linq.ConflictMode.ContinueOnConflict);
}
foreach (textdata dtdata in entities.textdatas)
{
Console.WriteLine(dtdata.dttime.Value.ToString());
}
Console.ReadLine();
}
}
}
I do change the loop from 100 to 200,300 to 400 etc before i run my app. But,the new records appear in the database and the old records are gone.
Edit again:
Here's my App.Config...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="ConsoleApplication2.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Can you just post your insert method? I think the problem is from your code not VS2010.
Unless you've also retrieved all the data and called DeleteOnSubmit for each of the retrieved elements, it shouldn't be deleting any data when you do an InsertOnSubmit. Items that are inserted result in SQL insert statements being generated when you call SubmitChanges. The only way that I know of to get a delete statement is to call DeleteOnSubmit. Perhaps, you are thinking that you need to remove the items from the table before calling submit changes to reduce the amount of data pushed back to the server. This isn't correct. Only the new or changed data will be sent back -- and calling DeleteOnSubmit will force the data to be removed when SubmitChanges is called.
My guess is that id is the key in database, but it is not autogenerated.
so when you create your new entities and assign them keys that already exist in db - db entries just get overriden by new ones.

Categories