I have a problem. I want to ask you all about how to back up database from vb.net. I'm using PostgreSQL. Why I need back up database? Because it's too large to display all at datagridview when it's running. So for a time span, example 3 months, it's automatically backed-up. I always get Messagebox "Error at or near Backup. Error while executingnonquer
Thank you
koneksi()
Try
Dim fname As String
Dim db2 As String = "aplikasilis2"
Dim strQuery As String
Dim objdlg As New SaveFileDialog
objdlg.FileName = "C : \Documents\Arsip 3 bulan_" + FormatTglUniversal(Date.Now) + ".bak"
objdlg.ShowDialog()
fname = objdlg.FileName
Dim data_affector As Integer
strQuery = "Backup database =" & db2 & " To disk ='" & fname & "'"
Try
cmdBackup = New OdbcCommand(strQuery, conn)
data_affector = cmdBackup.ExecuteNonQuery
MsgBox("berhasil")
Catch ex As Exception
MsgBox(ex.Message)
End Try
Catch ex As Exception
MsgBox(ex.Message)
End Try
You can't backup Postgresql use query as stated in comment by #jmcilhinney and the link to refer your question it's clear.
In Postgresql Documentation there are no information about that too:
Backup Use pg_dump or Backup
But using pg_dump will give you a full sql file including all DDL and DML statements to recreate your database in another place (or restore).
And Big system too like Odoo or iDempiere as ERP use database Postgresql do backup too using pg_dump command.
Odoo : How To Backup Odoo
iDempiere : How To Backup iDempiere
Just accept it you can't do that from Query statement and make meeting your project about this..
Related
I am using sql server with my VB.NET application where in multiple instance of the application is run from different server (CITRIX). I am sorting and picking up one individual Row for processing and immediately marking that row as picked in a column so that other instance doesn't pick up the same row and waste time. The issue is, in between picking up the row and updating as picked, another instance of the application is picking up the row. I have been suggested for using with DB Lock but the concept is not that much clear to me like whether it will solve my problem, whether I need admin right to use it (I do not have admin right in client DB) etc. Below is the code snippet I have used.
Dim MyConnection As SqlConnection
Try
MyConnection = New SqlConnection(connString)
MyConnection.Open()
Dim tableName As String = myTableName
Dim sqlQuery As String = "Select Top 1 * from " + tableName + " where "<some condition>
Dim MyCommand As SqlDataAdapter = New SqlDataAdapter(sqlQuery, MyConnection)
Dim DS as DataSet = New DataSet
MyCommand.Fill(DS, tableName)
If DS.Tables(0).Rows.Count >= 1 Then
sqlQuery = "UPDATE " + tableName + " SET Fld = #fld where Cond1= '" + DS.Tables(0).Rows(0).Item("Cond1").ToString + "'"
Dim cmd As New Data.SqlClient.SqlCommand(sqlQuery)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#fld", Data.SqlDbType.VarChar).Value = "Picked"
Try
cmd.Connection = MyConnection
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
Catch ex As Exception
MsgBox(ex.ToString)
Finally
MyConnection.Close()
End Try
I want it to make in such way that if an instance picks up a row, until it finishes updating the row, the row will not be visible to other instance with same query on the table, but other instance will continue to work with the other rows at the same time.
Two options I see:
Change your SELECT and UPDATE queries to a single UPDATE query. I didn't see where your SELECT was buying you anything.
If the SELECT is truly needed, then use a stored procedure on the database to handle the SELECT and the UPDATE on the database server side. You can lock the row during the transaction. See: Transaction Locking and Row Versioning Guide
Note that in general you should try to move your database queries to stored procedures. Not only does this reduce the amount of network traffic moving datasets back and forth, it increases the reliability, separates your database code from the UI, allows updates to the procedures without having to push new versions of the client application out and also avoids SQL injection.
I've researched and researched... yet to find a solution. I've read people having similar trouble because of the encoding, but I've tried retyping the query and even used convert to UTF-8 inside Notepad++. Any ideas?
Error:
Incorrect syntax near 'NEW'.
Query:
delete from [orgDefaults]
where ([orgcode] = N'NEW')
and ([ctlName] = N'AllowReportables')
This is being executed inside a VB.NET program I've created using this OLEDB driver:
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & updates_mdb & ";Jet OLEDB:Database Password=" & Settings.Password & ";")
You are using the wrong driver to connect to SQL server.
You are using the MS Access Jet Engine. But this uses another SQL syntax, that's why it does not work.
Just use the SQL Server OLEDB driver, and it will work.
Just for hack of it , try this:
Using conn As New SqlConnection("sqlServer Conn string - connectionstrings.com")
Dim sql As String = "DELETE FROM [orgDefaults] WHERE [orgcode] = #1 AND [ctlName] = #2"
Using cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#1", "NEW")
cmd.Parameters.AddWithValue("#2", "AllowReportables")
cmd.CommandType = CommandType.Text
conn.Open()
Dim retVal As Integer = cmd.ExecuteNonQuery()
If retVal > 0 Then
Debug.WriteLine("Success - deleted 1 or more records")
' remeber, retVal may not match num of rows deleted.
' Rather, it indicates total rows affected
Else
Debug.WriteLine("Still Success - deleted Nothing")
End If
End Using
End Using
This should give you better picture [if you have some "special" issue] because Sql executed this way will match your values and field types better.
When we are trying to backup our database we get an error.
Front End : VB.Net
Back End : SQL Server
DB Name : PROFITSTORAGE
Backup Location : 'D:\Profit\Data\ProfitStorage.Bak'
Code:
Dim con As New SqlConnection
Dim query As SqlCommand
Try
con.ConnectionString = "Server=(LocalHost);Data Source=LocalHost\SQLEXPRESS;Integrated Security=SSPI"
con.Open()
query = con.CreateCommand
query.CommandText = "BACKUP DATABASE PROFITSTORAGE TO DISK='D:\Profit\Data\ProfitStorage.bak' WITH INIT"
query.ExecuteNonQuery()
query.Dispose()
con.Close()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Backup Failed")
End Try
Query used :
BACKUP DATABASE PROFITSTORAGE
TO DISK='D:\Profit\Data\ProfitStorage.bak' WITH INIT
Error Message :
Cannot open backup device 'D:\Profit\Data\ProfitStorage.bak'. Operating system error 3 (failed to retrieve text for this error. Reason: 15105).
BACKUP DATABASE is terminating abnormally.
How to sort out this issue?
The query is not creating the folder if its not existing.
We should create a folder manually instead.
Since we are using VB.Net we had to create a folder with the following code before backup:
My.Computer.FileSystem.CreateDirectory("D:\Profit\Data\")
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" ;-)
I want to create a SQL Server database at runtime in my vb.net project. I know how to actually code the database but I am wondering where should I actually put the code? Should I be putting the code in the start up form or should it go into a class on it's own? Also, this project will be going on more than one pc at a particular site, so I only want the database to be created the first time the project is activated and then just be able query the database on different pcs after that. How do I do this? All help on this matter would be greatly appreciated.
EDIT:
Ok, so I should have been clearer on this. The project is going to be on 2 different pcs, it is for visitors entering a business. The pcs will be in reception and security. I need both pcs to access the same database with the same details in it. I don't want to have two different databases where details have to be put in twice. For example, if I enter at reception today and then go through security tomorrow, then all I should have to enter in security is why I'm entering the business again, I shouldn't have to put my details in a second time. How do I go about this? As I already said, I know how to code the database, but I want to know how to do what I stated in my question.
Thanks in advance for all help given.
If you add the code in module or in form load then it will execute all the time when the form loads. it is wasting of time to check whether the database exist or not in each run. So it is better to place a button with text "Create database" for this purpose(or menu item). it's click event will load the database. the following code can be used to create the database dynamically on button click
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'creating and initializing the connection string
Dim myConnectionString As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;Pooling=False")
'since we need to create a new database set the Initial Catalog as Master
'Which means we are creating database under master DB
Dim myCommand As String //to store the sql command to be executed
myCommand = "CREATE database my_db" //the command that creates new database
Dim cmd As SqlCommand = New SqlCommand(myCommand, myConnectionString) // creating command for execution
Try
cmd.Connection.Open() //open a connection with cmd
cmd.ExecuteNonQuery() //Execute the query
cmd.Connection.Close() //Close the connection
Catch
MsgBox(" Already installed database", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
End Try
'Creating table to the dynamicaly created database
Try
Dim cn As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=my_db;Integrated Security=True;Pooling=False")
'here the connection string is initialized with Initial Catalog as my_db
Dim sql As String //sql query string
sql = "CREATE TABLE customer(cus_name varchar(50) NULL,address varchar(50) NULL,mobno numeric(18, 0) NULL,tin varchar(50) NULL,kg varchar(50) NULL)"
cmd = New SqlCommand(sql, cn) // create command with connection and query string
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
Catch
MsgBox(" Already existing table", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
End Try
End Sub