Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to SQL Server 2008 Database via C# [closed]

I am attempting to connect to a database I created in SQL Server 2008 on my computer. I have a Windows Authentication login which looks like this:

try
{
  string sCon = @"Data Source=David-PC\SQLEXPRESS; Initial Catalog=ZarTrackDB; Integrated Security = true";
   SqlConnection dbConn;
   dbConn = new SqlConnection(sCon);
   dbConn.Open();
}
catch (Exception ex)
{
    MessageBox.Show(this, "An error occurd while attemtpting to connect to DB.\n" + ex.Message, "DB Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     return;
}

however it keeps throwing an exception:

Login failed for user David-PC\David

I am able to connect to the Master DB though:

 string sCon = @"Data Source=David-PC\SQLEXPRESS; Initial Catalog=Master; Integrated Security = true";

So i guess the probelm might be I do not have permissions? How do I go about giving myslef permissions to access this DB though when I login via SQL Server Management Studio I can insert create query etc on the ZarTrackDB perfectly.

I truly dont know what to do anymore please help!

EDIT:

here is a screen shot of my user mappings for the account I am trying to log in with:

User Mappings:

enter image description here

Server Roles:

enter image description here

UPDATE:

If I login to master and attempt to access ZarTrack :

   string sCon = @"Data Source=David-PC\SQLEXPRESS; Initial Catalog=Master; Integrated Security = true";
                SqlConnection dbConn;
                dbConn = new SqlConnection(sCon);
                dbConn.Open();

                string sql = "USE ZarTrackDB "+
"CREATE TABLE Customers ("+

"CustomerID int IDENTITY PRIMARY KEY NOT NULL," +
"CompanyName varchar(30) NOT NULL,"+
"CompanyAddress varchar(40) NOT NULL,"+
"Email varchar(40) NOT NULL,"+
"PhoneNumber varchar(15) NOT NULL"+
");";
                SqlCommand dbCmd = new SqlCommand();
                dbCmd.CommandText = sql;
                dbCmd.Connection = dbConn;

                dbCmd.ExecuteNonQuery();

I get Exception:

enter image description here

like image 294
David Kroukamp Avatar asked Jun 12 '26 20:06

David Kroukamp


1 Answers

It seems the

David-PC\SQLEXPRESS

was the problem when I do:

string sCon = @"Data Source=David-PC; Initial Catalog=ZarTrackDB; Integrated Security = true";
SqlConnection dbConn;
dbConn = new SqlConnection(sCon);
dbConn.Open();

It works perfectly

like image 51
David Kroukamp Avatar answered Jun 14 '26 10:06

David Kroukamp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!