How to connect to db via vb.net? - vb.net

I have the following code, the msgBox that says "DB changed" never shows up, and I get messages like follows in the immediate window.
But finally, the form loads, and I can't know whether my DB was created or not!
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim strConn As String = "Data Source=localhost;Initial Catalog=master;Integrated Security=True"
Dim conn As New SqlConnection(strConn)
conn.Open()
Try
conn.ChangeDatabase("productsDB")
MsgBox("DB changed")
Catch ex As Exception
Try
Dim command1 As New SqlCommand("CREATE DATABASE productsDB", conn)
command1.ExecuteNonQuery()
command1.Connection.ChangeDatabase("productsDB")
Dim command2 As New SqlCommand("CREATE TABLE products ([id][int],[name][char](30),[quantity][int],[dealer_price][int],[unit_price][int])", conn)
command2.ExecuteNonQuery()
Catch ex2 As Exception
MsgBox(ex2.Message)
End Try
End Try
End Sub

It might be helpful if you instantiate the connection, as well as open it, inside the try block to see the exception you are throwing.
Dim conn as SqlConnection
Try
conn = new SqlConnection(strConn)
con.Open()
...
Catch ex As Exception
MsgBox.Show(ex.Message)
End Try

Related

Fatal error encountered during command execution.'

I want to save the rows of datagridview into the database. I am using editbtn click button, when I press the button it gives me the following error: "Fatal error encountered during command execution." Here is the code which I am using
Private Sub Supplier_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn.ConnectionString = "Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;"
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
disp_data()
End Sub
Public Sub disp_data()
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "select * from supplier"
cmd.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New MySqlDataAdapter(cmd)
da.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub edit_btn_Click(sender As Object, e As EventArgs) Handles edit_btn.Click
Dim query As String = "updates supplier set nama=#nama, alamat=#alamat where npwp=#npwp"
cmd = New MySqlCommand(query, conn)
cmd.Parameters.AddWithValue("#nama", nama.Text)
cmd.Parameters.AddWithValue("#alamat", alamat.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Data berhasil di update")
disp_data()
End Sub
First of all, it's not good to re-use the same connection object throughout your application. There is a feature in ADO.Net called connection pooling, where the MySqlConnection object you use in your code is actually a simple wrapper for the real underlying connection. These real connections are much heavier and more expensive to manage. They handle the real work of authentication, getting network socket resources, negotiating with the server, etc.
When you try to re-use the same connection object, you are optimizing the small thing (MySqlConnection) at the expense of the big thing (the real underlying connections). Don't do that.
Instead, you really are much better off creating a new connection for most queries, and then returning it to the pool as quickly as possible. This is normally handled with a Using block.
That out of the way I can look at the actual question. I noticed the #npwp parameter is not defined in the last method. Guessing at the name of the appropriate field, you want something more like this:
Private Sub edit_btn_Click(sender As Object, e As EventArgs) Handles edit_btn.Click
Dim query As String = "updates supplier set nama=#nama, alamat=#alamat where npwp=#npwp"
Using conn As New MySqlConnection("Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;")
Using cmd As New MySqlCommand(query, conn)
cmd.Parameters.AddWithValue("#nama", nama.Text)
cmd.Parameters.AddWithValue("#alamat", alamat.Text)
cmd.Parameters.AddWithValue("#npwp", npwp.Text)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Data berhasil di update")
disp_data()
End Sub
Public Sub disp_data()
Dim dt As New DataTable()
Dim query As String = "select * from supplier"
Using conn As New MySqlConnection("Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;")
Using cmd As New MySqlCommand(query, conn)
Using da As New MySqlDataAdapater(cmd)
da.Fill(dt)
End Using
End Using
End Using
DataGridView1.DataSource = dt
End Sub

VB.NET SQL statement doesn't return any rows form Access database

I have the following code for a login winform. When I make the connection to the database and make a select statement I get no rows back. I'm getting the message "No data exists for the row/column."
But there are rows and columns in the database.
Can someone tell me what I do wrong?
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim connectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("MySqlConnectionString").ConnectionString
Using con As New OleDbConnection(connectionString)
Dim intResult As Integer = 0
' MsgBox(connectionString)
Try
con.Open()
Using cmd As New OleDbCommand("SELECT Gebruikersnaam FROM Gebruikers WHERE Gebruikers.Gebruikersnaam = #Username", con)
cmd.Parameters.AddWithValue("#Username", UsernameTextBox.Text)
cmd.Parameters.AddWithValue("#Password", PasswordTextBox.Text)
Using dr As OleDbDataReader = cmd.ExecuteReader()
'intResult = CInt(cmd.ExecuteScalar)
'If intResult > 0 Then
MsgBox(dr.Item("Gebruikersnaam").ToString)
'End If
With dr
While .Read()
MsgBox(.HasRows)
'MsgBox(.Item("Gebruikersnaam"))
'TextBox1.Text = .Item("Gebruikersnaam") & vbCrLf
End While
End With
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
Me.Close()
End Using
End Sub
The problem was checking dr.Item() before ever calling dr.Read(). Aside from the that, make sure the username in UsernameTextBox actually exists in the database, fix those nasty plain-text passwords, and you'll be fine.
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim connectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("MySqlConnectionString").ConnectionString
Try
Dim result As New StringBuilder()
Using con As New OleDbConnection(connectionString)
Using cmd As New OleDbCommand("SELECT Gebruikersnaam FROM Gebruikers WHERE Gebruikersnaam = #Username", con)
cmd.Parameters.AddWithValue("#Username", UsernameTextBox.Text)
cmd.Parameters.AddWithValue("#Password", PasswordTextBox.Text)
con.Open()
Using dr As OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
'MsgBox(dr("Gebruikersnaam"))
result.AppendLine(dr("Gebruikersnaam"))
End While
End Using
End Using
End Using
TextBox1.Text = result.ToString()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
One final concern. I'm not sure which OLE provider you're using, but last time I checked most providers where it makes sense to use OLE want you to use ? placeholders instead of named parameters. So the SQL command would look like this:
SELECT Gebruikersnaam FROM Gebruikers WHERE Gebruikersnaam = ?
But if you're really using MySql, as the connection string name suggests, you really do so much better getting the real MySql ADO.Net library instead of OleDB: minor performance gain, better error messaging, etc.

Fill datagrid with query

I am new to coding. Learn as I go, I want to fill a datagrid only with rows where my checkout is null
I want the specific data to show up on my datagrid that contain no checkout value. I have no clue what I am doing wrong. I am new in vb.
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
datafile = "D:\Projects\ezchain\ezchain\data\ex.accdb"
connec = provider & datafile
mycon.ConnectionString = connec
mycon.Open()
Dim str As String
str = "SELECT * from Keys WHERE checkout = '' "
Dim cmd As OleDbCommand = New OleDbCommand(str, mycon)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
mycon.Close()
Catch ex As Exception
MsgBox("Error")
mycon.Close()
Me.KeysTableAdapter.Fill(Me.ExDataSet.keys)
End Try
Me.KeysTableAdapter.Fill(Me.ExDataSet.keys)
End Sub
Atm nothing pops, not even exception ... o.O

VB.Net not able to connect to SQL

Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Server=localhost;Initial Catalog=acernis;User ID=root;Password=password"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
Currently in my code I have the code above the SQL username and pass are correct as is the DB. I have WAMP running and am using Navicat to make sure I can connect. What is wrong?
if you are using MS SQL server then your issue is with the connection string. try this one :
connetionString = "Server=localhost;Database=acernis;User ID=root;Password=password"
however if you mean MySQL then you need to change more than just the connectio string
try this:
Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim connetionString As String
connetionString = "Server=localhost;Database=acernis;Uid=root;Pwd=password;"
Dim conn As New MySqlConnection(connetionString)
Try
conn.Open()
MsgBox("Connection Open ! ")
Catch ex As MySqlException
MsgBox("Can not open connection Error: " & ex.ToString())
Finally
conn.Close()
End Try
End Sub
to find out what is the connection string that best suites you refer to the website
http://www.connectionstrings.com/
Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Server=localhost\<InstanceName>;Initial Catalog=acernis;User ID=root;Password=password"
cnn = New SqlConnection(connetionString)
Try
if not cnn.State=ConnectionState.Open then cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
As per observation, if you are using SQL Server, you need to specify the <Instance Name> in Server property.
Plus, do not use class Exception in catch section, Instead, use specific exceptoin class; in this case, use SQLException

i want save a picture into daatabase

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim a As New OpenFileDialog
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\USERS\USER\DOWNLOADS\SDP(BACKUP1)\SDP(BACKUP)\SDP.MDF;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Announcement ([name],[picture]) VALUES('" & nameTB.Text & "',#a2)"
cmd.Parameters.Add(New SqlClient.SqlParameter("#a2", SqlDbType.Image)).Value = IO.File.ReadAllBytes(PictureBox2.BackgroundImage)
cmd.ExecuteNonQuery()
MsgBox("Event Announcement submitted!")
con.Close()
Catch ex As Exception
MsgBox("Operation Failed! Please Check Again!")
End Try
End Sub
this is what i had try....i can choose a image but i cant save it(which mean complete save a picture into database) all that thing in google teach me save picture in sql server or access.. i had try it...but the very last thing i dunt understand is how can i parameter #a2 with picturebox?
it give error for IO.File.ReadAllBytes(PictureBox2.BackgroundImage)
As commented, File.ReadAllBytes wants a file, not an image. So you need to use a MemoryStream instead:
Using ms As New MemoryStream
PictureBox2.BackgroundImage.Save(ms, ImageFormat.Png)
cmd.Parameters.AddWithValue("#a2", ms.ToArray)
End Using