I cannot insert records into a SQL Server CE database. I have read lots of articles but I still did not receive a proper answer for that.
This is my code. Database is located in the bin folder of the project.
Dim strConnection As String
strConnection = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\Barcode_UAT.sdf;Persist Security Info=False"
Dim cn As New SqlCeConnection(strConnection)
If cn.State = ConnectionState.Closed Then
cn.Open()
End If
Dim cmd As SqlCeCommand
Dim sql As String = "insert into [tbl_Barcodes] ([SerialNo],[ItemId],[Date]) values (#SerialNo,#ItemId,#Date)"
Try
cmd = New SqlCeCommand(sql, cn)
cmd.Parameters.AddWithValue("#SerialNo", "12121333")
cmd.Parameters.AddWithValue("#ItemId", "Item01010")
cmd.Parameters.AddWithValue("#Date", "2012-2-2")
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch sqlexception As SqlCeException
MessageBox.Show(sqlexception.Message)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
cn.Close()
End Try
It seems like you are missing the bin folder in your Data Source location path
Related
Currently I used to back up my files in the way that, when user click on Backup the program will ask,
To Backup you must close your current session. This application will be closed now. Do you want to continue?
So the application will be closed and a new application will be launch in which if you click Backup it will copy the .mdf File and the .ldf File
|
But I have read in many pages that 'Copying the .mdf File and the .ldf File' is the unsafest way, so is there any other way to do Backup other than using SSMS because I want the user to be able to Backup within the Application.
|
Current code:
Sub Backup()
Dim con As New SqlClient.SqlConnection("data source=.\SQLEXPRESS;initial catalog=BQDB;Integrated Security=True")
Dim cmd As New SqlCommand()
Try
con.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = "Backup database BQDB To Disk='C:\Users\Zulfikar\BQBackup.BAK'"
cmd.Connection = con
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
|
Error Message Using Justin's Code
I tend to see a performance boost when using SqlCommands to backup databases.
Sub Backup()
Dim con As New SqlClient.SqlConnection("data source=DATASOURCE;initial catalog=NAME OF DATABASE;Integrated Security=True")
Dim cmd As New SqlCommand()
Try
con.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = "Backup database BQDB To Disk='C:\Users\Zulfikar\BQBackup.BAK'"
cmd.Connection = con
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Try
Dim path As String = String.Concat((Server.MapPath("~/temp/" + CCAM_Browe.FileName)))
CCAM_Browe.PostedFile.SaveAs(path)
Using OleDBcon As New OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + path + ";Extended properties=Excel 12.0;")
Using cmd As New OleDbCommand("Select * from [Sheet1$]", OleDBcon)
Using objAdapterr1 As New OleDbDataAdapter(cmd)
OleDBcon.Open()
Dim dr As DbDataReader = cmd.ExecuteReader()
Dim con_str As String = "Data Source=GFCKUL-A0027716\;Initial Catalog=Inbound_VSM;Integrated Security=True"
Using bulkInsert As SqlBulkCopy = New SqlBulkCopy(con_str)
bulkInsert.DestinationTableName = "test"
bulkInsert.WriteToServer(dr)
End Using
OleDBcon.Close()
lblMsg.Text = "Upload Successful"
File.Delete(Convert.ToString(CCAM_Browe.PostedFile.FileName))
End Using
End Using
End Using
Catch ex As Exception
lblMsg.Text = "Upload Unsuccessful, Please contact Administrator to assist"
End Try
The error occur at line OleDBcon.open(). I'm fed up with this problem , i currently installed Microsoft Excel 2013 32-bit .
This code work fine with if it's not Report Excel file.
Please help me! Thanks!
I am not sure if it's me or there's something wrong with my code. Whenever I try to add a new account, it is being "saved" and shown in my datagridview, however, when I check under the data set or the table data, it's not being saved (or updated). I am using Visual Studio 2013 and I just checked my Microsoft SQL version - 2012. I did what I found here and in other sites, like uncheck the "Prevent saving changes that require table re-creation"; and I also changed the "Copy to output directory to Copy if newer", oh, and I also changed the |DataDirectory| to the path of the 2 mdf files.
Sorry if I'm asking a question that was asked before. And... here's my code (this one is for change password form):
If txtNewPass.Text = txtRetyped.Text Then
Dim strSql As String
Try
Dim objAdap As SqlDataAdapter
Dim objDt As New DataTable
strConn = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FHGES.mdf;Integrated Security=True"
objConn = New SqlConnection(strConn)
Dim s As String = "SELECT * FROM tblAccounts WHERE UName COLLATE Latin1_General_CS_AS='" & frmLogin.txtUname.Text & "'AND PWord COLLATE Latin1_General_CS_AS='" & frmLogin.txtPassword.Text & "';"
objComm = New SqlCommand(s, objConn)
objAdap = New SqlDataAdapter(objComm)
objAdap.Fill(objDt)
lblUName.Text = objDt.Rows(0)(4).ToString
strSql = "UPDATE tblAccounts SET PWord='" & txtRetyped.Text & "' WHERE UName='" & lblUName.Text & "'"
objComm = New SqlCommand(strSql, objConn)
objConn.Open()
objComm.ExecuteNonQuery()
objConn.Close()
MessageBox.Show("Saved new password, please re-login", "FHGES", MessageBoxButtons.OK)
frmLogin.Show()
frmLogin.txtPassword.Clear()
frmLogin.txtPassword.Focus()
Me.Hide()
Catch ex As Exception
MsgBox(ex.Message)
Finally
If objConn.State = ConnectionState.Open Then
objConn.Close()
End If
End Try
Else
MessageBox.Show("Password don't match!", "FHGES", MessageBoxButtons.OK)
txtNewPass.Clear()
txtRetyped.Clear()
txtNewPass.Focus()
End If
The purpose of my application is when a user types in a customer, their username and a message into the respective textboxes, it's supposed to be recorded into a table on SQL Server after the user presses the send button.
Here's my code:
Public Class Form1
Dim Con As OleDbConnection
Dim cmd As New OleDbCommand
Dim conString As String = "Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password"
Public Sub MessageSent()
Try
Dim con As New OleDbConnection
con.ConnectionString = conString
con.Open()
cmd.Connection = con
cmd.CommandText = "insert into tblmessage(Customer, UserName, Message) values('" & txtCustomer.Text & "', '" & txtUserName.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Message Sent")
con.Close()
con.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
MessageSent()
End Sub
I'm getting the following error:
An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'.
What is it that I'm doing wrong and how can this be resolved.
It looks like you are trying to give a SQL Server connection string to an OleDbConnection. You need to either use a SqlConnection to open with that connection string or else you need to create a valid OLEDB connection string to point to that database. For reference, see this site.
When you want to connect to an MS SQL database you should use SQL connection instead of OleDbConnection.
The same is true for sqlCommand over the OldDbommand.
This SO question as some answers explaining the difference between Sql and OldDb Client.
Public Sub MessageSent()
Try
Using con As SqlConnection = New SqlConnection
con.ConnectionString = "Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password"
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblmessage(Customer, UserName, Message) values('" & txtCustomer.Text & "', '" & txtUserName.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
End Using
MsgBox("Message Sent")
con.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I think you are just missing this bit: Provider=SQLOLEDB;
For example:
Dim conString As String = "Provider=SQLOLEDB;Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password"
I am trying to display query results from SQL server in VB. I wrote following code, but not getting how to "Just display the results";
Public Function ConnectToSQL() As String
Dim con As New SqlConnection
Try
con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm"
Dim cmd As New SqlCommand("SELECT username FROM users WHERE username='user'", con)
con.Open()
Console.WriteLine("Connection Opened")
' Execute Query
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(String.Format("{0}, {1}", _
reader(0), reader(1)))
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection.
End Try
Return reader
End Function
Can any one guide? Thank you
I corrected a few things and now your function works fine for me:
Public Function ConnectToSQL() As String
Dim con As New SqlConnection
Dim reader As SqlDataReader
Try
con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm"
Dim cmd As New SqlCommand("SELECT username, WindowsLogin FROM users WHERE username='user'", con)
con.Open()
Console.WriteLine("Connection Opened")
' Execute Query '
reader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(String.Format("{0}, {1}", _
reader(0), reader(1)))
'NOTE: (^^) You are trying to read 2 columns here, but you only '
' SELECT-ed one (username) originally... '
' , Also, you can call the columns by name(string), not just by number '
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
'Return reader { note: reader is not valid after it is closed } '
Return "done"
End Function
Let me know if you have any questions.