I'm using Visual Basic 2008 here, and I'm debugging my code that connects to my SQL Database and writes something in it. It was working fine and all until I came to an error like this. NullReferenceException was unhandled. What's going on? Here is the code I'm working with:
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "server=...; user id=...; password=...; database=..."
Try
conn.Open()
Catch myerror As MySqlException
MsgBox("Error connecting to database")
End Try
Dim myAdapter As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM user WHERE username = '" + TextBox2.Text + "'"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
It highlights it right around conn.open(), and gives me that error. It was working fine earlier until I moved my sql database to my mac. (windows -> mac) Is there a difference? I backed up my stuff from my windows vista computer and restored it on my mac. I don't think there is a difference, but I'm just putting that out there. Why does this error come up?
Thanks,
Kevin
I would suggest reviewing your connection string. I used your code and connected to our local MYSQL db no errors.
I can't really say what the problem is off the top of my head.
But the way to find out would be to put a breakpoint on the conn=New MySqlConnection and look at the variables you have as you step through.
If the problem is happening on the conn.Open line then it would probably be because conn is null (nothing). But if that is the case then conn.ConnectionString should have thrown an exception.
The other step is to look at the stack trace of the exception and see where, exactly, it is being thrown from. It could, for example, be an error somewhere inside the mysql connector.
Sorry I can't really give you a definate answer, but I thought some general comments might help you to the solution or find some more detail.
Whivh version of MySql are you using? Have you looked at the details of this bug...
http://bugs.mysql.com/bug.php?id=26393
... which is related to idle time.
If you had the full stack trace associated with the exception then it might shed some light on the problem.
Related
I have tried existing post and none of the answers helped me solve the issue. Adding the piece of code.In the below code Dts.Transaction is null and hence
sqlConn.
SqlConnection sqlConn;
sqlConn = (SqlConnection)(Dts.Connections["connectionManager"].AcquireConnection(Dts.Transaction) as SqlConnection);
sqlConn.Open();
I have an SQL Task which returns a list of records to Script Task. I am trying to use connection manager to establish a connection. Not sure what is wrong. It's ADO.net connection manager.
Please do not mark this question as duplicate as the existing thread
did not help me.
This here is working for me:
SqlConnection sqlCon = new SqlConnection();
sqlCon = (SqlConnection)Dts.Connections["DMP"].AcquireConnection(Dts.Transaction) as SqlConnection);
I have tested this and though Dts.Transaction is null, the following is working for me (also note that rather than opening/closing the connection, you use acquire/release):
SqlConnection sqlConn = (SqlConnection)Dts.Connections["connectionManager"].AcquireConnection(Dts.Transaction);
...
Dts.Connections["connectionManager"].ReleaseConnection(sqlConn);
I've been trying to create a login page that will check if you're an administrator or a customer in my SQL data source. I am not sure why it can't understand the MySQLCommands. I added MySql.Data in the references but this doesn't seem to work.
This is where for example: MySqlConnection and MySqlCommand have blue underlinement.
Dim cmd As MySqlCommand = New MySqlCommand '(strSQL, con)
Password is a reserved word in MySql. If you want to use a field with that name then everytime you use it in your code you should remember to put it between backticks:
`password` = ...
Said that your code has serious problems. You should never concatenate strings coming from the user input to form a sql text. This leads to syntax errors caused by parsing problem and to Sql Injection attacks. You shoul use a parameterized query like this
strSQL = "SELECT name FROM employer WHERE (login=#login AND `password`=#pwd"
Dim cmd As MySqlCommand = New MySqlCommand(strSQL, con)
cmd.Parameters.Add("#login", MySqlDbType.VarChar).Value = strUser
cmd.Parameters.Add("#pwd",MySqlDbType.VarChar).Value = strPaswoord
con.Open()
If cmd.ExecuteScalar() = Nothing Then
....
Finally you should also change the way you get your data because you want to minimize the trips to access the database for performance reason. You should SELECT both the Name and the EMail with a single query and use an MySqlDataReader to get the data.
Other problems present in your code are the lack of appropriate using statement around the connection and the security problem caused by a possible clear text password stored in the database.
#GSerg asked me if I could right click and resolve.
I tried that but that was not an option.
After messing around with the error it appears that I had to write at top:
Imports MySql.Data.MySqlClient
I also had to add backticks when I used the word password for MySQL as #Steve reminded me.
Thank you for your help!
I am trying to remove all of the records from an SQL table in VB.net. My code for doing this is:
Dim SQL As String = "DELETE FROM MTable"
Using CN As New OleDb.OleDbConnection(AddPage.DBConnect)
CN.Open()
Dim DBcmd As New OleDb.OleDbCommand(SQL, CN)
DBcmd.ExecuteNonQuery()
CN.Close()
End Using
'SQLDataset.Tables("Mtable").Clear()
MtableTA.Update(SQLDataset)
SQL = "DELETE FROM ITable"
Using CN As New OleDb.OleDbConnection(AddPage.DBConnect)
CN.Open()
Dim DBcmd As New OleDb.OleDbCommand(SQL, CN)
DBcmd.ExecuteNonQuery()
CN.Close()
End Using
' SQLDataset.Tables("ITable").Clear()
ITableTA.Update(SQLDataset)
The Mtable and Itables are the SQL tables, while MtableTA and ItableTA are table adapters.
I also end up getting an error which states
An unhandled exception of type 'System.Data.DBConcurrencyException' occurred in System.Data.dll
Additional information: Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.
The section where this occurss is not provided in the code above, but is a call to MtableTA.update(SQLDataset). Any help would be very much appreciated. I'm also using OLEDB if that helps.
You have directly deleted the rows bypassing the TableAdapter methods to do that. So it is highly probable that when you call the Update there are some conflicts with data changed on the TableAdapter and no more available in the database.
After removing the rows directly using OleDbCommand.ExecuteNonQuery you should simply refresh the TableAdapters to sync them with the real situation on your physical database table
SQLDataset.Tables("ITable").Clear()
ITableTA.Adapter.Fill(SQLDataSet.ITable)
I'm trying to connect to a MySQL server via VB.NET, but my program keeps freezing on the con.Open() line.
Imports System.Data.SqlClient
Imports System.Data
....
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Server=000.000.000.000;Database=db_name;Uid=db_user;Pwd=db_pw;"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT * FROM courses"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
MessageBox.Show(lrd.ToString)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server: " & ex.Message)
Finally
con.Close()
End Try
The stuff in the connection string is the form of what I have in those spots, using those words as actual value placeholders for this example. Apart from containing the actual values, they are exactly identical. So if there are form errors (i.e. a missing apostrophe), please let me know. For the Server, am I supposed to put the IP address of the server or something else? Furthermore, in the reading loop, I'm not sure how to display all of the contents of the SQL query. Is what I have correct?
You are using ADO.NET for SQL Server instead of what you should be using, an ADO.NET client that works with MySQL, like MySQL Connector
You will need to install this and change SqlClient, SqlCommand, SqlConnection in your code to MySqlClient, MySqlCommand, MySqlConnection in accordance with how the MySQL Connector works.
To display first column values:
While lrd.Read()
MessageBox.Show(lrd.GetValue(0))
End While
I'm having some problems, when I do my query from my vb.net program to my mysql DB the data is sent, but its missing some things, let me explain.
My query is pretty simple I'm sending a file path to my DB so that after I can have a php website get the data and make a link with the data from my DB, but when I send my data the results look like this...
\server_pathappsInst_pcLicences_ProceduresDivers estCheck_list.doc
which should look like
\\server_path\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc
I don't know if its my code that's not good or my configurations on my mysql server please help...
Here's my code
'Construct the sql command string
cmdString = "INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES('" & filenameOnly_no_space_no_accent & "', '" & str_Lien_Nom_Procedure & "', '" & str_commentaires_Procedure & "')"
' Create a mysql command
Dim cmd As New MySql.Data.MySqlClient.MySqlCommand(cmdString, conn)
Try
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Catch ex As MySqlException
MsgBox("Error uppdating invoice: " & ex.Message)
Finally
conn.Dispose()
End Try
Sorry I got a call and could continue my comment so here's the rest :X
Well I guess that would work, but my program never uses the same path since in uploading a file on a server, so this time the document I wanted to upload was this path
\\Fsque01.sguc.ad\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc
but next time its going to be something else so I can't hard code the paths, I was looking more of a SQL query which that I might not know, since I already thought about searching my string and if it finds a backslash it adds another one, but I feel its not a good way to script the whole thing...
Anyway thanks a lot for your help
When you construct the insert SQL it doesn't have the backslashes escaped. For example:
INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES('\\server_path\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc
The backslashes need to be escaped like:
INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES('\\\\server_path\\apps\\Inst_pc\\Licences_Procedures\\Divers\\test\\Check_list.doc
You can do this with something like (not sure about VB.NET):
filenameOnly_no_space_no_accent = filenameOnly_no_space_no_accent.Replace("\\", "\\\\")
You should also look into parameterised queries, which may protect you from some SQL injection attacks and are a bit easier to write and maintain compared to stitched-together SQL (this isn't tested and I'm not familiar with MySQL parameterised queries so YMMV):
cmdString = "INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES(?nom, ?lien_nom, ?commentaires)"
Dim cmd As New MySql.Data.MySqlClient.MySqlCommand(cmdString, conn)
cmd.Parameters.Add("?nom", filenameOnly_no_space_no_accent.Replace("\\", "\\\\"))
cmd.Parameters.Add("?lien_nom", str_Lien_Nom_Procedure)
cmd.Parameters.Add("?commentaires", str_commentaires_Procedure)
This is based on something I found at this end of this tutorial.
Use double backslashes not single backslash
cmdString = "INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES(?nom,?Lien_Nom,?Commentaires)"
' Create a mysql command
Dim cmd As New MySqlCommand(cmdString, conn)
cmd.Parameters.AddWithValue("?nom", filenameOnly_no_space_no_accent)
cmd.Parameters.AddWithValue("?Lien_Nom", str_Lien_Nom_Procedure)
cmd.Parameters.AddWithValue("?Commentaires", str_commentaires_Procedure)
Try
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
Catch ex As MySqlException
MsgBox("Error uppdating invoice: " & ex.Message)
Finally
conn.Dispose()
End Try