Click here to Skip to main content
15,899,314 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone,

I have a project in school , and I'm having a trouble to connect tables in c#, and I have a database in SQL. Can anyone help me ? Any help would be great.

The situation is like this:
I've got two tables.
First got a field with the primary key, and the second has just the field without key.

How to make the relationship between two tables?!

Best regards !
Posted

Hi
the solution is not as simple as you might think it is.

First of all you need to connect to the database from your C# program.
To connect to MS SQL Server database from C#.NET, you need to create a connection string such as below:

private SqlConnection connection;
private string connectionString =
@"Server=(local);Database=Embedding_SQL_Test;User ID=sa;Password=123";
connection = new SqlConnection( connectionString );

Next, you use the SqlConnection object created above to create a 'SqlCommand', as shown below:
SqlCommand cmd = new SqlCommand( "select * from Customer where CustomerID = @Cid", connection);

The SQL query shown here can be replaced by a SELECT, INSERT, UPDATE queries etc.

Next to execute the SQL queries in the database, you use the following methods:
ExecuteReader - to execute SELECT queries
ExecuteNonQuery - to execute INSERT, DELETE, UPDATE, and SET statements.

This is a very short description of how to connect to SQL Server database from C# and execute SQL queries in the database.
For details about the connection string, the methods and their parameters check the following link: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html )
Here you will also find details about how to pass parameters to the SQL queries as well as calling stored procedures and much more.
 
Share this answer
 
Sounds like you need to know about Foreign Keys. Have a look at these knowledge-base articles:
MSDN: FOREIGN KEY Constraints[^]
MSDN: Creating and Modifying FOREIGN KEY Constraints[^]

For more details: MSDN: Creating and Modifying Tables[^]
 
Share this answer
 
If there is no column in the second table that has a reference to the key in the first table (this is called a Foreign Key), you have no way of connecting the two tables.

Whatever you're doing, the primary key value in one table must how up in a column in the second table, otherwise you have no relationship.
 
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