Add new column in vb.net database
Here are the steps to add a new column to a database table in VB.NET:
Using SQL Server
- Create a connection to your database using the
SqlConnection
class:Dim conn As New SqlConnection("Data Source=<your_server>;Initial Catalog=<your_database>;User ID=<your_username>;Password=<your_password>") conn.Open()
- Create a
SqlCommand
object to execute the SQL query:Dim cmd As New SqlCommand("ALTER TABLE <your_table_name> ADD <new_column_name> <data_type>", conn)
Replace
<your_server>
,<your_database>
,<your_username>
,<your_password>
,<your_table_name>
, and<new_column_name>
with your actual database credentials and table information.
For example:
Dim cmd As New SqlCommand("ALTER TABLE Customers ADD EmailAddress VARCHAR(50)", conn)
-
Execute the SQL query:
cmd.ExecuteNonQuery()
Using ADO.NET
-
Create a connection to your database using the
SqlConnection
class:Dim conn As New SqlConnection("Data Source=<your_server>;Initial Catalog=<your_database>;User ID=<your_username>;Password=<your_password>") conn.Open()
-
Create a
DataTable
object to represent the table:Dim dt As New DataTable("Customers")
-
Add the new column to the
DataTable
:dt.Columns.Add("EmailAddress", Type.GetType("System.String"))
-
Update the database table using the
DataAdapter
:Dim da As New SqlDataAdapter("SELECT * FROM Customers", conn) da.Update(dt)
Using Entity Framework
-
Create a
DbContext
object:Dim db As New YourDbContext()
-
Use the
DbSet
property to access the table:Dim customers As DbSet(Of Customer) = db.Set(Of Customer)()
-
Add the new column to the table using the
DbSet
property:customers.Entity.SetColumn("EmailAddress", "string")
-
Save the changes to the database:
db.SaveChanges()
Note: The above examples are for adding a new column to an existing table. If you want to add a new table, you can use the
CREATE TABLE
SQL statement or theDbSet
property with theCreateTable
method.