Can anyone give me an idea on how to save the datas that are typed into a textbox (multiline) in vb.net 2010 to my database (mysql)?
Use a String-representation of your Object and store this String to your database. JSON might be useful for you here, JSON.net is commonly used...
Here is a code to insert a record in a mysql database:
Let's say you have a mysql database called (myDB) and a table called (myTable).
There are two fields in myTable: ID(int) and TextBoxData(Text)
Imports MySql.Data.MySqlClient
Imports System.Data.OleDb
Public Class Form1
Dim conn As New MySqlConnection
Sub connect()
Dim DatabaseName As String = "myDB"
Dim server As String = "ip address here"
Dim userName As String = "username here"
Dim password As String = "password here"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, userName, password, DatabaseName)
Try
conn.Open()
MsgBox("Connected")
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub
End Class
' The following code is used to write to MySQL database:
Try
conn.Open()
Catch ex As Exception
End Try
Dim cmd As New MySqlCommand(String.Format("INSERT INTO `myTable` (`ID` , `TextBoxData`) VALUES ('{0}' , '{1}')", "", TextBox1.Text))
cmd.ExecuteNonQuery()
conn.Close()
Source: VB.NET connect to MySql Server
Related
I am working on to connect my App form VB.Net with MySQL table database with this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String = "data source=localhost;Initial Catalog=tabledb;user id=root;password=password1234"
Dim con As New SqlConnection(str)
con.Open()
Dim com As String = "Select * from springdata where rfid_tag='" & Rfid_tagTextBox.Text & "'"
Dim cm As New SqlCommand(com, con)
Dim rd As SqlDataReader = cm.ExecuteReader()
If rd.Read() = True Then
MessageBox.Show("Valid username and password")
Else
MessageBox.Show("Invalid username and password", caption:="login")
End If
End Sub
But when I run the app gave me this error:
Additional information: A network-related or instance-specific error
occurred while establishing a connection to SQL Server. The server
was not found or was not accessible. Verify that the instance name
is correct and that SQL Server is configured to allow remote
connections. (provider: Named Pipes Provider, error: 40 - Could not
open a connection to SQL Server)
What is the correct ConnectionString to use with MySQL 5.7.
The connection string below is an SQL Server connection string:
Dim str As String = "data source=localhost;Initial Catalog=tabledb;user id=root;password=password1234"
According to MySQL Connector .NET connection string, you should provide server name, port number (if using different port), database name and credentials like this:
Dim str As String = "Server=localhost;Port=3306;Database=tabledb;Uid=root;Pwd=password1234"
Also you should use MySqlConnection, MySqlCommand & MySqlDataReader instances with parameters instead of value concatenation inside query string (ensure that reference to MySql.Data.dll added first):
Using con As New MySqlConnection(str)
con.Open()
Dim com As String = "Select * from springdata where rfid_tag=#tag"
Using cm As New MySqlCommand(com, con)
cm.Parameters.Add("#tag", MySqlDbType.VarChar).Value = Rfid_tagTextBox.Text
Dim rd As MySqlDataReader = cm.ExecuteReader()
' Check if any rows exist
If rd.HasRows = True Then
' do something
Else
' do something else
End If
End Using
End Using
I am using MYSQL database for that...I get this following Error...Please anyone can help me?
Imports System.Data
Imports MySql.Data Imports MySql.Data.MySqlClient
Public Class formLogin
Dim connStr As String = "server=localhost;user=root;database=ssknet;port=3306;password=;"
Dim connection As New MySqlConnection(connStr)
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
connection.Open()
Dim cmd As New MySqlCommand("SELECT * FROM user WHERE username=#username and password=#password", connection)
cmd.Parameters.Add("#username", MySqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#password", MySqlDbType.VarChar).Value = txtPassword.Text
Dim adapter As New MySqlDataAdapter
Dim table As New DataTable
adapter.Fill(table)
If table.Rows.Count <= 0 Then
MessageBox.Show("Invalid Username or Password")
Else
MessageBox.Show("Login Success!")
End If
'cmd.ExecuteNonQuery()
connection.Close()
End Sub
End Class
I want to access database right now. Quick frnds
You are missing a critical step. You are not assigning any command to your adapter. It doesn't know how to query anything without a command
Dim adapter As New MySqlDataAdapter(cmd)
Next, according to the MySql Reserved KeyWords, user and password are reserved and to use them in a query as field names you should put backticks (ALT+096) around them. So the query should be written as
Dim cmd As New MySqlCommand("SELECT * FROM `user`
WHERE username=#username
AND `password`=#password", connection)
A part from this your code is good enough albeit there are a couple of thing to consider.
First, connection object should not be kept as global objects. This leads to many problems with the resources kept on the server and with closing/opening the connection when there is an error. Just create and discard the connection inside a using statement
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Using connection = New MySqlConnection(connStr)
connection.Open()
.... all of your code except the close connection
End Using ' this close the connection also in case of exceptions
Second, you don't need an SqlDataAdapter and a datatable if you just want to check if the user/password exists
Dim reader = cmd.ExecuteReader()
if reader.HasRows then
MessageBox.Show("Login Success!")
Else
MessageBox.Show("Invalid Username or Password")
End If
Third, it is a great security risk to keep password in plain text inside your database and then using queries to retrieve it. You should use Salt and Hashing methods to store and retrieve password
i want to connect with mysql phpmyadmin database and get data in my application in vb.net but i can not connect.i got error message that unable to connect with specified host.
when i entered 10.1.1.53/phpmyadmin in my browser i am able to open my all database without any password or username but when i try to connect with my vb.net application by clicking button i got error message.
this is my code. please help me.
ImportsMySql.Data.MySqlClient
PublicClasslogin
Dim con AsMySqlConnection
Dim reader AsMySqlDataReader
Dim command AsMySqlCommand
DimmyconAsString = "server=10.1.1.53/phpmyadmin;database=dbtest"
PrivateSubbtnlogin_Click(sender AsObject, e AsEventArgs) Handlesbtnlogin.Click
login()
EndSub
PrivateSublogin()
con = NewMySqlConnection
con.ConnectionString = mycon
Try
con.Open()
Catch ex As Exception
EndTry
EndSub
PrivateSubbtnexit_Click(sender AsObject, e AsEventArgs) Handlesbtnexit.Click
Me.Close()
EndSub
EndClass
Public Sub login()
Dim DatabaseName As String = "dbtest"
Dim server As String = "10.1.1.53"
Dim userName As String = "username"
Dim password1 As String = "pass"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, userName, password1, DatabaseName)
Try
conn.Open()
' MsgBox("Connected")
Catch ex As Exception
MsgBox(ex.Message)
End Try
'conn.Close()
End Sub
the one that u gave me is DimmyconAsString << is that typo?
As a Vb noob im working on this school project. I need to insert my values into my mysql database but for a reason it isn't inserting tried everything but i can't find why it isn't inserting.
Thx in advance
Dim sqlCommand As New MySqlCommand
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim strStockSQL As String
Dim server As String = "localhost"
Dim DatabaseName As String = "Gip"
Dim userName As String = "root"
Dim password As String = ""
SQLConnection = New MySqlConnection()
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, userName, password, DatabaseName)
Try
strStockSQL = "insert into stock (Barcode,Naam_Product,Verkoopprijs) values (#Barcode,#Naam_product,#Verkoopprijs)"
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = strStockSQL
sqlCommand.Parameters.AddWithValue("#Barcode", Convert.ToString(txtBarcode.Text))
sqlCommand.Parameters.AddWithValue("#Naam_product", Convert.ToString(txtNaam.Text))
sqlCommand.Parameters.AddWithValue("#Verkoopprijs", Convert.ToInt32(txtVP.Text))
sqlCommand.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Error occured: Could not insert record")
When executing an sqlCommand you must have it's related connection object in open state.
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
SQLConnection.Close()
Also, read about Using statement and use it for SqlConnection.
Another thing: this code line is meaningless: If Not conn Is Nothing Then conn.Close() remove it.
So i tried to connect my sql database to my vb project but it gives me this error:
Error Connecting to Database : Authentication to host "for user" using
method 'mysql_native_password' failed with message : Acces denied for
user "#'N56VB' (using password : NO)
N56VB is my pc
UPDATE the error wich I get now is : A first chance exception of type
'System.ArgumentException' occurred in System.Data.dll
Additional information: Keyword not supported.
If there is a handler for this exception, the program may be safely
continued
I dont know what to do anymore it will be a stupid I guess ,be easy on me i'm a noob :(
I hope someone knows the problem
Imports MySql.Data.MySqlClient
Imports System.Data.Sql
Imports System
Imports System.Data
Public Class NieuweItems
Public dbconn As New MySqlConnection("Data Source=localhost;user id=root;password=;database=gip;")
Dim conn As New MySqlConnection
Private Sub btn_return_Click(sender As Object, e As EventArgs) Handles btn_return.Click
Me.Close()
SalesApplication.Show()
End Sub
Private Sub btn_inlezen_Click(sender As Object, e As EventArgs) Handles btn_inlezen.Click
Dim sqlCommand As New MySqlCommand
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim strStockSQL As String
SQLConnection.ConnectionString = "Data Source= localhost ;user id = root'#'localhost; password = ;database=gip;table=stock;"
Try
conn.Open()
strStockSQL = "INSERT INTO Barcode " & txtBarcode.Text & "INSERT INTO Naam_Product" & txtNaam.Text & "INSERT INTO Verkoopprijs" & txtVP.Text
sqlCommand.ExecuteNonQuery()
SQLConnection.Close()
conn.Close()
Catch myerror As MySqlException
MessageBox.Show("Error Connecting to Database: " & myerror.Message)
Finally
conn.Close()
End Try
End Sub
End Class
I presume that the error is occurring inside the "btn_inlezen_Click" event handler? I think what's happening is that you're declaring a new empty MySqlConnection, opening the connection inside your Try block and only then are you setting the ConnectionString. Because MySqlConnection was declared with no parameters it might be trying to use N56VB as the user account and this doesn't have any permissions on your MySQL db.
So set your connection string before opening the connection.