Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey, how do i connect a database which i hav created in sql server 2012 to c# successfully. Help appreciated..
Posted

Try setting up a connection in VS with the Server Explorer pane:
1) Open Server Explorer.
2) Right click "Data connections" and select "Add connection"
3) In the dialog that follows, select your DataSource, and database, specify the security info, and press the "Test connection" button.
4) When the connection works, press "OK"
5) Highlight your database in the Server Explorer pane, and look at the Properties pane. A working example of the connection string will be shown, which you can copy and paste into your app or config file.
Then it's just code:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("SELECT iD, description FROM myTable", con))
        {
        using (SqlDataReader reader = com.ExecuteReader())
            {
            while (reader.Read())
                {
                int id = (int) reader["iD"];
                string desc = (string) reader["description"];
                Console.WriteLine("ID: {0}\n    {1}", iD, desc);
                }
            }
        }
    }
 
Share this answer
 
You may want to start with finding the correct connection string for SQL Server 2012 here for instance: Connection strings for SQL Server 2012[^].
You may also need to configure your SQL Server for remote access if you're not running your programs on the same machine where the SQL Server lives: The minimum requirements to access a remote SQL Server 2012 Database[^].

Regards,

—Manfred
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900