create a new database table in csharp

To create a new database table in C#, you need to perform the following steps:

  1. First, establish a connection with the database using a connection string. You can use ADO.NET libraries for this purpose.
main.cs
string connectionString = "server=localhost; database=myDatabase; uid=myUsername; password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);
169 chars
3 lines
  1. After establishing the connection, create a SQL query to create a new table in the database. You can use SqlCommand object to create the query.
main.cs
string query = "CREATE TABLE myTable (id INT PRIMARY KEY, name VARCHAR(50), age INT)";
SqlCommand command = new SqlCommand(query, connection);
143 chars
3 lines
  1. Execute the query using the ExecuteNonQuery method of SqlCommand object.
main.cs
connection.Open();
command.ExecuteNonQuery();
connection.Close();
66 chars
4 lines

The complete code for creating a new database table in C# is shown below:

main.cs
string connectionString = "server=localhost; database=myDatabase; uid=myUsername; password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);

string query = "CREATE TABLE myTable (id INT PRIMARY KEY, name VARCHAR(50), age INT)";
SqlCommand command = new SqlCommand(query, connection);

connection.Open();
command.ExecuteNonQuery();
connection.Close();
380 chars
10 lines

Note: Replace the connection string with your own database connection details and modify the query according to your requirements.

related categories

gistlibby LogSnag