VB.Net not able to connect to SQL - 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

Related

vb.net windows form select query using postgresql server

I am new in vb.net, how do i conduct select query in my windows forms using postgresql server?
this is my connection, (actually i dont know if this is working but i didnt receive any error and the message box appear if i button is clicked)
here is code so far
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MyCon As New Odbc.OdbcConnection
MyCon.ConnectionString = "Driver={PostgreSQL ANSI};database=*****;server=localhost;port=5432;uid=postgres;sslmode=disable;readonly=0;protocol=7.4;User ID=******;password=*****;"
MyCon.Open()
If MyCon.State = ConnectionState.Open Then
MsgBox("Connected To PostGres", MsgBoxStyle.MsgBoxSetForeground)
End If
End Sub
In .Net we have Using...End Using blocks that will close and dispose objects that use unmanaged code. Connections fall into this type of object; any object class that has a .Dispose method.
You can pass your connection string directly to the constructor of the connection.
We also have Try...Catch...Finally....End Try for exception handling.
To test your connection:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=*****;server=localhost;port=5432;uid=postgres;sslmode=disable;readonly=0;protocol=7.4;User ID=******;password=*****;")
MyCon.Open()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
For help with the connection string itself check https://www.connectionstrings.com/postgresql/
There are several ways to query your database in ADO.net. Study up on ADO.net. The following is one way.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=*****;server=localhost;port=5432;uid=postgres;sslmode=disable;readonly=0;protocol=7.4;User ID=******;password=*****;"),
cmd As New Odbc.OdbcCommand("Select * From SomeTable;", MyCon)
MyCon.Open()
dt.Load(cmd.ExecuteReader)
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
DataGridView1.DataSource = dt
End Sub

Trying to submit new records to an access file [.mdb] through VB forms

Just a school student working on their project. Tried researching but had no luck, hope you can help.
What I currently have coded for the form I wish to make inputs with is below.
Imports System.Data.OleDb
Public Class frmPlayerInput
Dim Provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private Sub btnHome_Click(sender As Object, e As EventArgs) Handles btnHome.Click
frmHome.Show()
Me.Hide()
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "Z:\Desktop\players.mdb"
connString = Provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "Insert into Items ([FirstName].[Surname].[TopNumber]) Values (?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("FirstName", CType(txtFirstName.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Surname", CType(txtSurname.Text, String)))
cmd.Parameters.Add(New OleDbParameter("TopNumber", CType(txtTopNumber.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
txtFirstName.Clear()
txtSurname.Clear()
txtTopNumber.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnClear.Click, btnHome.Click
txtFirstName.Clear()
txtSurname.Clear()
txtTopNumber.Clear()
End Sub
End Class
the error message: System.InvalidOperationException: 'Not allowed to
change the 'ConnectionString' property. The connection's current state
is open.'
This happens because you are opening your connection and then not closing it if an exception is thrown. This is an example of why you should be creating, using and destroying such objects locally. The most proper way to use a connection object is like this:
Using connection As New OleDbConnection(connectionString)
'Use connection here.
End Using
That will create a new connection object each time, which is the preferred option. It is a lightweight object, with the actual database connection at a lower level. The Using block also guarantees that the connection will be closed, even if an unhandled exception is thrown within the block.
and the other error that opens in the form is: Number of query values
and destination fields are not the same
This happens because, as I said, you're using dots where you should be using commas. [FirstName].[Surname].[TopNumber] is being interpreted as one column with a qualifying table and schema rather than three columns.

Object of instance not set to an instance or an object. Visual Basic

I am writing a simple piece to insert 5 values into my local database. The connection gets established well but when I press the button , which does the job for inserting into the DB I get "Object of instance not set to an instance or an object" this message.
Sql version
Microsoft SQL Server 2014 - 12.0.2000.8 (X64)
Here is My code
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form1
Dim ID As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim SQLCon As New SqlConnection With {.ConnectionString = "Server=DIONISIS-PC\SQLEXPRESS; Database=Testing;Trusted_Connection=True;"
}
Dim SQLcmd As SqlCommand
Try
SQLCon.Open()
Label2.Text = "Connected"
Catch ex As Exception
Label2.Text = "ERROR"
MsgBox(ex.Message)
Finally
SQLCon.Close()
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SQLCon As New SqlConnection With {.ConnectionString = "Server=DIONISIS-PC\SQLEXPRESS; Database=Testing;Trusted_Connection=True;"
}
Dim SQLcmd As SqlCommand
ID += 1
Dim LastName As String = TextBox1.Text
Dim firstName As String = TextBox2.Text
Dim Address As String = TextBox3.Text
Dim city As String = TextBox4.Text
Try
SQLCon.Open()
SQLcmd.Connection = SQLCon 'EDIT: The problem seems to be here'
SQLcmd.CommandText = "INSERT INTO students([student_ID], [LastName],[FirstName],[Address],[City]) VALUES([ID], [LastName],[firstName],[Address],[city])"
SQLcmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
SQLCon.Close()
End Try
End Sub
End Class
This should work for you:
SQLcmd.CommandText = ("INSERT INTO students([student_ID], [LastName],
[FirstName],[Address],[City]) VALUES({1},'{2}','{3}','{4}','{5}'"),LastName
,firstName,Address,city)
BUT you will be prone to SQL Injection. The correct way to do this is described here and it's name is by using SQL Parameters
You need to instantiate SQLcmd before trying to set properties on it.

How to connect to db via 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

“syntax error in INSERT INTO statement”

I'm a beginner in vb.net
I've got the following Error upon executing the Insert-Statement
syntax error in INSERT INTO statement
Here is my code:
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(?,?,?)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("?", txtid)
.Parameters.AddWithValue("?", txtuser)
.Parameters.AddWithValue("?", txtpass)
.ExecuteNonQuery()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Could anyone help me?
Try to use sql parameter names
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("#ID", txtid)
.Parameters.AddWithValue("#Username", txtuser)
.Parameters.AddWithValue("#Password", txtpass)
.Open()
.ExecuteNonQuery()
.Close()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Note that: You should properly close your connections after you use them. Therefore following code may be better.
Private Sub InsertLogin()
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Using con As New OleDbConnection(ConnectionStringHERE)
Using cmd As New OleDbCommand
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#ID", txtid)
cmd.Parameters.AddWithValue("#Username", txtuser)
cmd.Parameters.AddWithValue("#Password", txtpass)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
InsertLogin()
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Here, I used cmd. syntax, it is no different then using With.
You have to name the sql parameters.
Look at the examples in the documentation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue%28v=vs.110%29.aspx