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
Related
Error Message: Exclusive access could not be obtained because the
database is in use. restore database is terminating abnormally.
My Backup code works but I don't know why this restore code doesn't work.
Try
Dim con2 As SqlConnection
Dim com2 As SqlCommand
Dim filename2 As String
Dim strquery2 As String
Dim database2 As String
Dim get_servername2 As String
'get the value selected in Database Name Dropdown Menu
database2 = Database_NameComboBox.Text
'get the value selected in Server Name Dropdown Menu
get_servername2 = Server_NameComboBox.Text.Trim
Dim opendlg As New OpenFileDialog
Dim constr2 As String
' set SQL connection data source using default Master Database
constr2 = "Data Source=" & get_servername2 & ";Initial Catalog=master;Integrated Security=SSPI"
' open SQL Database to restore
If opendlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Me.Cursor = Cursors.WaitCursor
con2 = New SqlConnection(constr2)
con2.Open()
filename2 = opendlg.FileName
strquery2 = "Restore database " & database2 & " from disk='" & filename2 & "'"
' execute command
Try
com2 = New SqlCommand(strquery2, con2)
com2.ExecuteNonQuery()
MessageBox.Show("Database " & database2 & " has been Restored Successfully", "IBP Legal Aid Case Management System - Restore Database", MessageBoxButtons.OK, MessageBoxIcon.Information)
con2.Close()
Me.Server_NameComboBox.SelectedIndex = -1
Me.Database_NameComboBox.SelectedIndex = -1
Me.Database_NameComboBox.Enabled = False
Me.Cursor = Cursors.Default
Catch ex As Exception
Me.Cursor = Cursors.Default
MessageBox.Show(ex.Message)
End Try
End If
Catch ex As Exception
Me.Cursor = Cursors.Default
MessageBox.Show(ex.Message)
End Try
Prior to restore you should be sure there is no user connected to this database, otherwise you get the error you posted.
You can first set your db offline and then restore:
alter database MyDB set offline
with rollback immediate;
restore database ...
I am having a few issues regarding reading data from a local sql server in visual basic. I have made the database and connected it as a data source but for some reason my data source connection and initial catalog must be incorrect. This is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
con.ConnectionString = ("Data Source = localhost; Initial Catalog=Database1Dataset; Integrated security=true ")
cmd.Connection = con
con.Open()
cmd.CommandText = "select login, password from Table where login = '" & tboxUname.Text & "' and password = '" & tboxPword.Text & "' "
rd = cmd.ExecuteReader
If rd.HasRows Then
frmProperties.Show()
Else
MsgBox("Incorrect Login") 'Else, display a message saying "incorrect login".
Tries += 1
If Tries = 3 Then
MsgBox("Closing Program")
Close()
End If
End If
End Sub
My database is called Database1 and the table is called Table. Thanks for any help.
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
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'm trying to retrieve data from sql server to vb.net textbox but i don't know what else to do all the tutorials i have are just to retrieve records from the database to datagrid view..please help..
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
cn.Open()
With cmd
.Connection = cn
.CommandText = "SELECT * FROM Students WHERE RFID like '%" & txtrfid.Text & "%'"
End With
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
cn.Close()
txtname.Text = 'Firstname'
You're populating a DataTable with the data from the database so you then have to get the data from that DataTable into the TextBox. You can do that with data binding, which is how you've probably seen it done with a grid, e.g.
txtname.DataBindings.Add("Text", dt, "Firstname")
That's definitely how you'd do it if you were retrieving multiple records that you wanted to be able to navigate, although you'd probably use a BindingSource in between. If there's only one record then you might instead just move the data manually, e.g.
txtname.Text = CStr(dt.Rows(0)("Firstname"))
If you want to display only a single value (FirstName) from Table then see following piece of code
Using conn As New SqlConnection("connstr")
conn.Open()
Dim cmd As New SqlCommand("", conn)
Dim txtName As String
cmd.CommandText = "SELECT firstname FROM Students WHERE RFID ='" & txtrfid.Text & "'"
txtName = IIf(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
If txtName <> "" Then
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
Textbox1.Text = ""
Textbox1.Text = txtName
else
MsgBox("No Record Found!", MsgBoxStyle.Information, "INFO.")
End If
End Using
There are many ways to retrieve the data. You can simply retrieve the data from sql database to textbox using sql data reader which is one of my favourite. Let me share to you.
Note : Don't forget to import system.data.sqlclient
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
strConn = "Data Source=" & servernamehere & ";Initial Catalog=" & databasenamehere & ";User ID=" & userid & ";Password=" & password
sqlConn = New SqlConnection(strConn)
sqlConn.Open()
Dim sqlcmd As New SqlCommand("Your query here", sqlConn)
Dim myreader As SqlDataReader
myreader = sqlcmd.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
txtrfid.Text = myreader.Item("column name from sql database table").Tostring
End If
sqlConn.Close()
End Sub
You may catch the exception with Try-Catch Technique.