I'm done coding in vb.net with mysql as my database. And also I'm done exporting mysql database into .sql file and done building my code into an application, but there's a problem, when im trying to run my application in other computer, my application didnt read the exported mysql database file. can anyone help me how to fix this? i've attached some few lines of my code if someone ask my code.
Dim query As String
Dim count As Integer
sqlcon = New MySqlConnection
sqlcon.ConnectionString =
"server=localhost;userid=root;password=root;database=svfmemberlistdb"
Try
sqlcon.Open()
query = " SELECT * FROM svfmemberlistdb.account where username='" & txtUser.Text & "' and password='" & txtPass.Text & "' "
sqlcmd = New MySqlCommand(query, sqlcon)
sqlrdr = sqlcmd.ExecuteReader
count = 0
While sqlrdr.Read
count = count + 1
End While
If count = 1 Then
Me.DialogResult = DialogResult.OK
MessageBox.Show("Login Successful")
Me.Hide()
ElseIf count > 1 Then
MessageBox.Show("Username or Password are Duplicated")
Else
MessageBox.Show("Login Failed, Invalid Username or Password")
End If
sqlcon.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
this is the error message appear when i try to run my build application with it's database in other computer.
Related
I'm new to Mysql databases. I created and connected successfully a database for the local server. But "A connection attempt failed..." error arise when trying to read data from a table. "Insert into ..." statement is working. I searched for whole web for the reason. Not success. Anyone can help, please. Thank in advance...
Complete error description:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Relevant Code as follows:
following function Working and Connected successfully
Public Function Connect() As Boolean
Dim Status As Boolean
Try
conn.ConnectionString = "Server=" & Server & ";Port=3306;Database=" & DBName & ";User ID=" & UID & ";Password=" & Pwd & ";CharSet=utf8;"
conn.Open()
cmd.Connection = conn
If conn.State = ConnectionState.Open Then
Status = True
End If
Catch ex As Exception
ErrorMsg = ex.Message
Status = False
End Try
Return Status
End Function
Following Function returns the error...
Public Function getData(ByVal SQLStr As String) As MySql.Data.MySqlClient.MySqlDataReader
Dim tmpDR As MySql.Data.MySqlClient.MySqlDataReader
If conn.State = ConnectionState.Open Then
cmd.CommandText = SQLStr
tmpDR = cmd.ExecuteReader()
Else
MsgBox("Database not connected...", MsgBoxStyle.Exclamation, "Connection Error")
tmpDR = Nothing
End If
getData = tmpDR
End Function
Get rid of any class level database objects. Get rid of the Function Connect altogether. If you ever start to write
If conn.State = ConnectionState.Open Then
you should know you are doing it wrong.
Don't pass DataReader's around. The connection must remain open for them to function. Load a DataTable and pass that after the connection and command are disposed by the Using block.
If you intend to show a message box to the user, let exceptions bubble up to the user interface code.
Private ConStr As String = "Server=" & Server & ";Port=3306;Database=" & DBName & ";User ID=" & UID & ";Password=" & Pwd & ";CharSet=utf8;"
Public Function getData(ByVal SQLStr As String) As DataTable
Dim dt As New DataTable
Using conn As New MySqlConnection(ConStr),
cmd As New MySqlCommand(SQLStr)
conn.Open
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
As you can see, it only takes one simple line to create a connection. Connections are precious resources and should only be opened directly before the .Execute... and closed as soon as possible.
I am trying to make a secure login for my database, using a MySQL database.
Private Sub logIn_Click(sender As Object, e As EventArgs) Handles logIn.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server=localhost;userid=root;password=Catawba;database=catawbapartnership"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "select * from database.admininfo where admin_username= ' " & TB_UN.Text & " ' and admin_password= ' " & TB_PD.Text & " '"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
If count = 1 Then
MessageBox.Show("Username and Password Accepted")
ElseIf count > 1 Then
MessageBox.Show("Username and Password Are Incorrect")
Else
MessageBox.Show("Username and Password Are Incorrect")
End If
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try`
This is the code, but I keep getting the error of Unknown database'database'
In MySQL Workbench, the entire database is named catawbapartnership
And the table I need to get info from is called admininfo
But, it keep saying I have entered it incorrectly. Please help!
Remove database. from your code. As a default database is in the connection you don't need to specify it in the question.
Please copy your implementation from somewhere else. This has SQL injection vulnerabilities and you should never store plain text passwords.
OWASP has a lot of guidance on being a responsible programmer.
I have a pc program used by dozens of people, and with the increase in people connecting to a database, the program began to throw the error with a large number of database connections. I checked the database after each query creates a process that is in the database as "sleep" if you exceeded the number 50 is the above error crashes. How can I remedy this if the problem lies with the program or hosting?
Database screen ;
http://obrazki.elektroda.pl/5375287900_1423553806.png
Code:
Public Sub loginUser(ByVal sql As String)
Try
Dim maxrow As Integer
con.Open()
dt = New DataTable
With cmd
.Connection = con
.CommandText = sql
End With
da.SelectCommand = cmd
da.Fill(dt)
maxrow = dt.Rows.Count
If maxrow > 0 Then
Form1.Show()
Else
Label3.Text = ("Invalid Username or Password!")
Label3.Visible = True
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
da.Dispose()
End Sub
Private Sub InsertData()
sql = "SELECT * from users WHERE login = '" & (username.Text) & "' and pass = '" & StringtoMD5(password.Text) & "'and banned = '" & 0 & "'"
loginUser(sql)
End Sub
When using database connections a special care should be used to correctly close and dispose these connections. If you don't do that correctly you end up with stale connections kept by your program and never reused by the pooling infrastructure of ADO.NET (See ADO.NET Connection Pooling)
The code in your example above has all the checks in place and should not be the cause of your problems but, are you sure that every where in your program you follow the same pattern without forgetting to dispose the involved objects?
The using statement is a life saver here because, EVEN in case of exceptions, you could be sure that the objects enclosed by the using statement are closed and disposed returning any unmanaged resources back to the system.
Another problem is your way to build SQL Commands concatenating strings. This leads directly to SQL Injection attacks and a very poor security standard for your application.
Said that, I think you should change your loginUser method to something like this
Public Sub loginUser(ByVal sql As String, ByVal parameterList as List(Of MySqlParameter))
Try
Dim maxrow As Integer
' local variables for connection, command and adapter... '
Using con = new MySqlConnection( ..connstring here.. )
Using cmd = con.CreateCommand()
con.Open()
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddRange(parameterList.ToArray())
End With
Using da = new MySqlDataAdapter(cmd)
Dim dt = New DataTable
da.Fill(dt)
maxrow = dt.Rows.Count
If maxrow > 0 Then
Form1.Show()
Else
Label3.Text = ("Invalid Username or Password!")
Label3.Visible = True
End If
End Using
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
And call it with
Private Sub InsertData()
sql = "SELECT * from users " & _
"WHERE login = #uname " & _
"AND pass = #pwd " & _
"AND banned = '0'"
Dim parameterList = new List(Of MySqlParameter)()
parameterList.Add(new MySqlParameter("#uname", MySqlDbType.VarChar))
parameterList.Add(new MySqlParameter("#pwd", MySqlDbType.VarChar))
parameterList(0).Value = username.Text
parameterList(1).Value = StringtoMD5(password.Text)
loginUser(sql, parameterList)
End Sub
As I have said, just this change alone probably don't fix your problem. You should try to find in your program where you have a situation in which the connection is not properly closed and disposed. (and, at least, replace that code with the using statement)
Ok from the answer from the previous question the reasoning still applies here but this time A different issue. There is a login system (Loginvb.vb) that I got for the launcher I was creating and was wondering 2 things:
Is there a better way to do the Login check with the database (as in
more secure) (the login style will have a web based registration
setting via PHP script)?
Is there a way to take a certain column (labled as access) in the database and put it
as a public string so I can check if it will equal 1 2 or 3 in a
different form labeled as Main.vb
Here is the current login check:
Public Sub login_Click(sender As Object, e As EventArgs) Handles login.Click
If txtuserName.Text = "" Or txtpassWord.Text = "" Then
MsgBox("You cannot progress until you login....(moron =p)")
Else
'Connects To the Database
Dim connect As MySqlConnection
connect = New MySqlConnection()
connect.ConnectionString = "server=127.0.0.1;user id=sc;Password=derp;database=sclaunch" 'not the actual login ;)
Try
connect.Open()
Catch myerror As MySqlException
MsgBox("Error Connecting to Database. Please Try again !")
End Try
'SQL Query To Get The Details
Dim myAdapter As New MySqlDataAdapter
Dim sqlquerry = "Select * From login where username = '" + txtuserName.Text + "' And password= '" + txtpassWord.Text + "'"
Dim myCommand As New MySqlCommand()
'My fail attempt at what I am trying to do :(
Dim sql22 As MySqlConnection
sql22 = New MySqlConnection()
sql22.ConnectionString = "Select * From login where access ="
'End of fail attempt
myCommand.Connection = connect
myCommand.CommandText = sqlquerry
'Starting The Query
myAdapter.SelectCommand = myCommand
Dim mydata As MySqlDataReader
mydata = myCommand.ExecuteReader
'To check the Username and password and to validate the login
If mydata.HasRows = 0 Then
MsgBox("Invalid Login")
Else
'fail testing xD
Label3.Text = sql22
MsgBox("You are now Loged In!")
End If
End If
End Sub
Still basically learning more and more as I am coding all this got to love trial and error and the moments where you get stuck =/ (Sorry to the admins or whatever for fixing tag issues still new to the site xD)
Assuming that the same table login that contains the credentials contains also the access column that you want to retrieve, then I have changed a lot of your code
Dim sqlquerry = "Select * From login where username = #name AND password=#pwd"
Dim myCommand As New MySqlCommand(sqlquery, connect)
myCommand.Parameters.AddWithValue("#name", txtuserName.Text)
myCommand.Parameters.AddWithValue("#pwd", txtpassWord.Text)
Dim mydata = myCommand.ExecuteReader
If mydata.HasRows = False Then
MsgBox("Invalid Login")
Else
' the same record that contains the credentials contains the access field'
mydata.Read()
Label3.Text = mydata("access").ToString()
MsgBox("You are now Loged In!")
End If
What I have changed:
Removed the string concatenation and added the appropriate parameters
Removed myAdapter and every references to it (not needed, you don't
fill DataTable/DataSet)
Removed sql22 and every references to it. It's a Connection and you
try to use like a Command
Fixed the check on HasRows (Returns a boolean not an integer. Are you
using Option Strict Off?)
I already have this coded out (more or less) in Java for Linux OS, however I am not familiar enough with the syntax of .net to translate my Java code into VB2010 code... So I was hoping someone here could help me out with this.
The issue:
I am trying (as the title says) to create folders on my windows box based on the entries in our customer database (we have a lot, so i'm not about to do them by hand lol).
I want to use VB.net to create a program that will loop a query through the SQL database, take the customerIDs of our clients, and create folders for each of those names in a specific directory.
My Java code that I need to translate:
//Initializers
Statement stmt;
ResultSet rs;
rs = stmt.executeQuery("SELECT CustomerID FROM customerlist;");
System.out.println("Creating customer user database:\n");
while(rs.next()){
String str1 = rs.getString("CustomerID");
try {
// Create user & Home Directory
Process p = Runtime.getRuntime().exec("sudo useradd " + str1 + " --shell /bin/sh -m " );
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println("Created user: \t" + str1);
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
Thread.sleep(100);
} catch (IOException e) {
e.printStackTrace();
}
}
I need the vb code to do the same thing, but only create the folder, and for the windows OS.
Important notes:
I am using Imports MySql.Data.MySqlClient to make the db connection.
it is a REMOTE mysql server, not a local one (don't know if this note was needed).
We have close to 6,000 clients... (thus why i'm NOT doing it by hand!)
The boss says to switch from Java to VB, so no arguing the point of sticking to Java please..
Seeing as how people are thinking that i'm asking for a handout for the entire program... here is what I have so far:
Private Sub ButtonLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonLogin.Click
conn = New MySqlConnection()
conn.ConnectionString = "server=xxx" & ";" & "user id=xxx" & ";" & "password=xxx" & ";" & "database=companysqldb"
Try
conn.Open()
MessageBox.Show("Connection Opened Successfully")
'while loop pseudo
'------------------
'set query string to "SELECT CustomerID FROM customerlist;"
'while looping through query
'set stringvar to current loop's CustomerID
'Create directory
If(Not System.IO.Directory.Exists("c:\pub\users\" & stringvar)) Then System.IO.Directory.CreateDirectory("c:\pub\users\" & stringvar)
RichTextBox.AppendText(vbCrLf & "Added folder: " & stringvar)
RichTextBox.ScrollToCaret()
'end while loop
Catch myerror As MySqlException
MessageBox.Show("Error Connecting to Database: " & myerror.Message)
End Try
End Sub
As you can see, I have most of it already written out, however my primary difficulty is the syntax of the while loop and the SQL Query.
SOLUTION:
Well, after several hours of scouring the net, I finally managed to find the solution I was looking for.
changed:
conn.Open()
MessageBox.Show("Connection Opened Successfully")
'while loop pseudo
'------------------
'set query string to "SELECT CustomerID FROM customerlist;"
'while looping through query
'set stringvar to current loop's CustomerID
'Create directory
If(Not System.IO.Directory.Exists("c:\pub\users\" & stringvar)) Then System.IO.Directory.CreateDirectory("c:\pub\users\" & stringvar)
RichTextBox.AppendText(vbCrLf & "Added folder: " & stringvar)
RichTextBox.ScrollToCaret()
'end while loop
to
conn.Open()
MessageBox.Show("Connection Opened Successfully")
Dim command As New MySqlCommand("SELECT CustomerID from customerlist", conn)
Dim stringvar As String
Dim count As Integer = 1
myReader = command.ExecuteReader
While (myReader.Read())
stringvar = myReader(0).ToString
If (Not System.IO.Directory.Exists("c:\pub\users\" & stringvar)) Then
System.IO.Directory.CreateDirectory("c:\pub\users\" & stringvar)
TextBox.AppendText(vbCrLf & count & ": Created folder for CustomerID: " & stringvar)
TextBox.ScrollToCaret()
Else
TextBox.AppendText(vbCrLf & count & ": Could *NOT* creat folder for CustomerID: " & stringvar)
TextBox.ScrollToCaret()
End If
count = count + 1
End While
Produced:
CustomerID: 11112
CustomerID: 11113
CustomerID: 11114
cmd.Connection = conn
conn.Open()
Dim cnt As Integer
Dim CustCode As String
cmd.CommandText = "Select * from Checks"
rd = cmd.ExecuteReader
While rd.Read()
cnt = cnt + 1
End While
If cnt = 0 Then
cnt = cnt + 1
Else
cnt = cnt + 1
End If
CustCode = "Cust_00" & cnt
TextBox1.Text = CustCode
rd.Close()