I have an application in VB.net and SQL Server 2019 database, and now is installed on on many client computers, but now in the NEW Version of the app I modify the SQL schema. For example in Table1 I added 3 new columns, in Table2 I add 1 column etc.
How can I update from VB.NET application when new app is UPDATED? How can I compare the database schema in the clients server and my last SQL SCHEME
I tried this but this is not good idea because I need to write many many tables and columns what I change
con = New SqlConnection(cs)
' con.Open()
' Dim cb2 As String = "if not exists (select *
' from
' INFORMATION_SCHEMA.columns
' where
' table_name = 'Company'
' and column_name = 'VersioniDB')
' alter table
' Company
'add
'[VersioniDB] [nchar](20) NULL"
' cmd = New SqlCommand(cb2)
' cmd.Connection = con
' cmd.ExecuteNonQuery()
' con.Close()
Related
I am looking for help for creating a function to sort a database I have on a SQL Server in which I can search for name and part number. I have my database connected to visual studio but struggling to connect to database within code and being able to generate the database on the data grid view.
Anything helps, thanks
There are a couple of concepts you'll need to implement:
Connect to the database
Setup your SQL command with the necessary WHERE clause
Fill a DataTable with the results
Bind the DataTable to the DataGridView
Here is an example, I've heavily commented the code to explain what is going on:
' wrap code in Try/Catch because database operations can fail
Try
' create a new instance of the connection object
Using connection = New SqlConnection("My Connection String Here")
' create a new instance of the command object
Using command = New SqlCommand("Select * From MyTable WHERE Name = #name AND PartNumber = #part", connection)
' parameterize the query
command.Parameters.Add("#name", SqlDbType.VarChar, 100).Value = "my name search"
command.Parameters.Add("#part", SqlDbType.VarChar, 100).Value = "my part number search"
' open the connection
connection.Open()
' create a new instance of the data adapter object
Using adapter = New SqlDataAdapter(command)
' fill a DataTable with the data from the adapter
Dim table = New DataTable()
adapter.Fill(table)
' bind the DataTable to the DataGridView
MyDataGridView.DataSource = table
End Using
' close the connection
connection.Close()
End Using ' disposal of command
End Using ' disposal of connection
Catch ex As Exception
' display the error
MessageBox.Show(ex.Message)
End Try
How to fill combobox in vb.net with column name from Microsoft Sql Server? I have table name called Table_Categories. I wish to fill the combobox with the column names of that table . I am also planning on adding column names in the table using vb.net as its front end . how can I do it ?
Public Sub Categories()
Dim Connect As New SqlConnection
Dim Adapter As New SqlDataAdapter
Dim DataTable As New System.Data.DataTable
Dim Query As String
ConnectionString = "Data Source=LUSPOC-PC;Initial Catalog=Sales_Invnetory;Integrated Security=True"
Connect = New SqlConnection(ConnectionString)
Connect.Open()
Connect.ChangeDatabase("Sales_Inventory")
Query = "select Column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Table_Categories'"
Adapter.SelectCommand = New SqlCommand(Query, Connect)
Adapter.Fill(DataTable)
Admin.items_category_combobx.DataSource = DataTable
Admin.items_category_combobx.DisplayMember = "Column_name"
Admin.items_category_combobx.ValueMember = "Column_name"
End Sub
Connect.ChangeDatabase("database-name")
Query = "select Column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='your-Table-name'"
Admin.items_category_combobx.DataSource = DataTable
Admin.items_category_combobx.DisplayMember = "Column_name"
Admin.items_category_combobx.ValueMember = "Column_name"
Change your query as above and you will get column names in your dataset. For adding column, take column name and type from user. build and execute an alter table query for adding column from it.
Using sqlconn As New SqlConnection("your connection string")
sqlconn.Open()
Using SqlCommand As New SqlCommand("select Column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Table_Categories'", sqlconn)
SqlCommand.CommandTimeout = 0
Using sqlAdp As New SqlDataAdapter(SqlCommand)
sqlAdp.Fill(dt)
End Using
End Using
End Using
ComboBox1.DataSource = dt
ComboBox1.DataTextField = "Column_name"
ComboBox1.DataValueField = "Column_name"
ComboBox1.DataBind()
I am trying to UPDATE database table rows using SQLCommandBuilder with datatable rows using the following test code. One table with a primary key column and one datatable to keep it simple.
Using the following code, the dbo.Dogs2 table is "appended" with the datatable rows - therefore doubling the number of rows rather than just updating the changed row(s)
If I add the code table.AcceptChanges() just before the Dim builder As New SqlCommandBuilder(adapter), the database table dbo.Dogs2 remains unchanged.
If I add the code table.AcceptChanges() just before the adapter.Update(table), the database table dbo.Dogs2 remains unchanged.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' dbo.Dogs2 database table columns are exactly like datatable columns with exception of dog names
' only UPDATING the "Name" field (no Inserts or deletes)
' orginal dog names "Name" in Dogs2.dbo are Sharpy, Bully, Shep, Charlie, and Yorky
' new dog names "Name" in Dogs2.dbo are June, Tucker, Maggie, Charles, and Candy
' Dex_Row_Id is the primary key with Identity Increment set to 1
' Create a DataTable with five columns.
'
Dim table As New DataTable()
table.Columns.Add("Weight", GetType(Integer))
table.Columns.Add("Name", GetType(String))
table.Columns.Add("Breed", GetType(String))
table.Columns.Add("Size", GetType(Char))
table.Columns.Add("Date", GetType(DateTime))
table.Columns.Add("Dex_Row_Id", GetType(Integer))
'
' Add data to the DataTable
'
AddDogRow(table, 57, "June", "Shar Pei")
AddDogRow(table, 130, "Tucker", "Bullmastiff")
AddDogRow(table, 92, "Maggie", "Anatolian Shepherd Dog")
AddDogRow(table, 25, "Charles", "Cavalier King Charles Spaniel")
AddDogRow(table, 7, "Candy", "Yorkshire Terrier")
ShowResult(table) 'displays datatable correctly (this is a DevExpress.com Reference/Extension)
'
' Create new SqlConnection, SqlDataAdapter, and builder.
'
Dim cnString As String = "<<<SQLConnectionString>>>"
'
Using cnSQL1 As New SqlConnection
cnSQL1.ConnectionString = cnString
Using adapter = New SqlDataAdapter("SELECT * FROM Dogs2", cnSQL1)
ShowResult(table) 'displays datatable
Dim builder As New SqlCommandBuilder(adapter)
adapter.UpdateCommand = builder.GetUpdateCommand()
builder.RefreshSchema()
Using New SqlCommandBuilder(adapter)
'
' Fill the DataAdapter with the values in the DataTable.
'
adapter.Fill(table)
ShowResult(table) 'displays datatable + original table data
' Open the connection to the SQL database.
'
cnSQL1.Open()
' Update the SQL database table with the values.
'
adapter.Update(table)
' dbo.Dogs2 now has 10 rows (the 5 rows from the dataset + the original 5 rows)
End Using
End Using
End Using
End Sub
You are using incorrectly the adapter. You should first load the rows from the database, then update the retrieved rows and finally call the update.
' REMOVE THE CODE BEFORE THIS '
' Create new SqlConnection, SqlDataAdapter, and builder.'
Dim cnString As String = "<<<SQLConnectionString>>>"
Dim table = New DataTable() ' Leave it emtpy and without schema'
Using cnSQL1 As New SqlConnection
cnSQL1.ConnectionString = cnString
Using adapter = New SqlDataAdapter("SELECT * FROM Dogs2", cnSQL1)
Dim builder As New SqlCommandBuilder(adapter)
adapter.UpdateCommand = builder.GetUpdateCommand()
' no need of this -> builder.RefreshSchema()'
Using New SqlCommandBuilder(adapter)
adapter.Fill(table)
ShowResult(table) 'displays original table data'
' no need of this -> cnSQL1.Open()'
' NOW YOU COULD CHANGE THE ROWS, FOR EXAMPLE'
table.Rows(0)("Weight") = 99
' Update the SQL database table with the values.'
adapter.Update(table)
End Using
End Using
End Using
When you pass an existing table to the Fill method of the Adapter, the existing record are not removed and thus your table is filled with data from the database and from your manual creation of the table (Of course the Adapter build for you the table columns. Moreover, the rows added manually to your table are marked with the DataRowState.Added while the row modified by your code will be marked with the DataRowState.Changed. This state helps the Update command to decide which action to perform on every row present in the table (Of course the rows that are not changed maintain the initial DataRowState.Unchanged
Finally, calling AcceptChanges doesn't mean that the rows will be updated on the database table. Only the DataRowState flag is reset to the DataRowState.Unchanged
I am working on an application which backs up database tables and stores their data as CSV. When I want to restore a table back to the database I use a 'model' table which creates an existing table based on the model.
However there are multiple structures of these tables and I would like to generate the tables' 'Create' script and save it somewhere for restoring purposes.
Is there anyway for this? I am only interested to do this via coding and not sql script because we are using both SQL Server and Oracle and this process will be automated for more than 3000 tables.
In the code below I create the table based on a table model:
If ProductData.Tables(0).Rows(0).Item(0) = 0 Then 'Does not exist
'Create table based on a model
Dim sqlCopyFromModel As New SqlCommand("SELECT TOP 0 * INTO " & sFileName & " FROM s_20130702;", con)
con.Open()
Dim i As Integer = sqlCopyFromModel.ExecuteNonQuery()
con.Close()
'Enter data from CSV file
Dim sqlInsertDataFromCSV As New SqlCommand("BULK INSERT " & sFileName & " FROM '" & txtFilePath.Text.Trim & "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', FIRSTROW=2 )", con)
con.Open()
sqlInsertDataFromCSV.ExecuteNonQuery()
con.Close()
MsgBox("success")
In Oracle you can use builtin package DBMS_METADATA where the function GET_DDL can give you the DDL ("create script") needed to create the table.
http://docs.oracle.com/database/121/ARPLS/d_metada.htm#ARPLS66885
SELECT DBMS_METADATA.GET_DDL('TABLE','EMP','SCOTT')
FROM DUAL;
(If you are trying to do something that is database independent and works both on SQL Server and Oracle, then you'd better not use "TOP 0" ;-)
What is the correct connection string and what are the requirements for connecting to Sql Server 2008 database from Visual Basic 6?
' Initialize variables.
Dim cn As New ADODB.Connection
Dim provStr As String
' Specify the OLE DB provider.
cn.Provider = "sqloledb"
' Specify connection string on Open method.
ProvStr = "Server=MyServer;Database=northwind;Trusted_Connection=yes"
cn.Open provStr
For illustration only (Ref.):
Set rsOrders = New Recordset
rsOrders.Open "Select * from orders", cn
Do While Not rsOrders.EOF
'
' If the order matches some custom business logic then get the details for
' that order, without opening a new connection.
'
If SomeBusinessLogic(rsOrders("CustomerID")) Then
Dim rsDetails As Recordset
Set rsDetails = New Recordset
'
' Open a new recordset using the same connection. Normally it's not
' possible to have two recordsets simultaniously using the same
' connection, but MARS makes this possible
'
rsDetails.Open "Select sum(quantity * unitprice) as total " & _
"from [order details] " & _
"where OrderID=" & rsOrders("OrderID"), _
cn
grandTotal = grandTotal + rsDetails("total")
End If
rsOrders.MoveNext
Loop
lblTotalOrders = grandTotal
You would use ADODB. And here are some connection string samples.
Public Cnn As New ADODB.Connection
Cnn.Open Provider=SQLNCLI10;Server=10.1.100.1;Database=DataJualLama;Uid=sa;Pwd=sa;
It required to install sql server 2008 native client runtime from microsoft site.