I just want to ask what is the difference between ? and # when inserting data to mysql in visual basic. So I have this query:
Dim sql As String = "INSERT INTO users(firstname, lastname, position) VALUES(?fname, ?lname, ?pos)"
cmd = New MySqlCommand(sql, conn)
cmd.Parameters.AddWithValue("?fname", TextBox1.Text)
cmd.Parameters.AddWithValue("?lname", TextBox2.Text)
cmd.Parameters.AddWithValue("?pos", TextBox3.Text)
I first use the #param but it is not inserting data to mysql but when I use ?param it inserts data. What is the difference between them?
When CommandType is set to Text, the .NET Framework Data Provider for
ODBC does not support passing named parameters to an SQL statement or
to a stored procedure called by an OdbcCommand. In either of these
cases, use the question mark (?) placeholder.
Direct quote from here:
named parameters with .NET Framework Data Provider for ODBC
Related
I am using some legacy project and I need to export some files from my Lotus Notes database to MySQL DB using ODBC connection.
I have a ~94000 documents in lotus database with some small attachments (30-40kb).
As always, for this tasks I was always using some kind of this:
Dim mysqlConnection As New ODBCConnection
Dim sqlQuery As New ODBCQuery
Dim result As New ODBCResultSet
Dim notesSession As New NotesSession
Set ntsDatabase = notesSession.CurrentDatabase
Call mysqlConnection.ConnectTo("DSN_NAME","NAME","PASS")
And I was not having problems with sending/parsing some data with queries like this:
Set sqlQuery.Connection = mysqlConnection
Set result.Query = sqlQuery
sqlQuery.SQL = some query e.t.c.
Everything is working fine. But now I am trying to find a way to send files to MySQL database and having some real problems to find the solution.
Can you please give some small example with sending a small blob file to MySQL or some kind of advise to solve this?
Thanks!
I don't think an example like that could be considered "small".
You're going to have to extract the attachment to a file, read the file into NotesStream, convert the bytes in the NotesStream into a Base64 string, and send that string value in a SQL command.
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'm making a program in which the label text will change according to the retrieved data. But the only thing/command I found are retrieving data by column or by record. I need to get only a single data/cell.
I already know how to connect and use sql commands in Vb.net by as I said earlier I can't retrieve a single data/cell.
I found a function called mysql_fetch_array but I think It's only for Php not for Vb or I am I mistaken?
This will do it for you !
- you need the limit command added to your query !
- for better performance i suggest using order by !
Dim conn as MySqlConnection
Dim cmd As MySqlCommand
conn = New MySqlConnection("server=localhost;user id=root;password=;database=db_name;")
conn.Open()
cmd = New MySqlCommand("SELECT col_name FROM table_name WHERE col_name='values' LIMIT 1", conn)
For example, in sql
all ` should be replaced with `` right?
Well, is there a function built in by vb.net that does that sort of thing already?
That way I do not have to encode it.
By the way, I do not access sql database directly. Basically I am creating a text file and that text file contains raw sql statements. Most of the answers deal with accessing sql data directly.
I don't think so as I think the only case where something like this would be relevant is if you were doing inline SQL Commands without parameters.
This has a risk of SQL Injection, and therefore you should create commands like this:
Dim cmd As New SqlCommand("UPDATE [TableA] SET ColumnA=#ColumnA WHERE ID=#ID", Conn)
cmd.Parameters.Add("#ColumnA", SqlDbType.NVarChar).Value = txtColumnA.Text
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ID
cmd.ExecuteNonQuery()
Dont try and do this! I know you are trying to avoid SQL Injection so you are to be commended for thinking about security. However rolling your own sanitisation routine is something that is easy to get wrong.
Use parameters in your query along the lines of
cmd.CommandText = "select * from customer where id=?id";
cmd.Parameters.AddWithValue("?id",CustomerIDValue);
If you are using a string then you'll be using " in your code so you won't need to escape these characters.
Dim mySql As String = "SELECT `MyColumn` FROM `Table`"
I have the following MySqlCommand:
Dim cmd As New MySqlCommand
cmd.CommandText = "REPLACE INTO `customer` VALUES( ?customerID, ?firstName, ?lastName)"
With cmd.Parameters
.AddWithValue("?customerID", m_CustomerID)
.AddWithValue("?firstName", m_FirstName)
.AddWithValue("?lastName", m_LastName)
End With
I have a class that handles execution of MySqlCommands and I'd like to have it log every query to a file. I can retrieve the query/command being executed with:
cmd.CommandText
but that just returns the original CommandText with the parameters (?customerID, ?firstName, etc.) and not the actual substituted values added by the AddWithValue functions. How can I find out the actual "final" query that was executed?
I did the following:
dim tmpstring as string = MySqlCommand.CommandText
For each p as MySqlParameter in MySqlCommand.parameters
tmpstring = tmpstring.replace(p.ParameterName, p.Value)
Next
This seems to output everything you need
I havn't seen a method for this.
And in any case, prepared statements are sent to the server with the ?customerID,?firstname parameters, and then the actual parameters are sent seperately - the mysql driver doesn't build up a final sql query like you'd do if you didn't use prepared statements.
The parameterised method you're using should be okay for preventing SQL injection.
.AddWithValue("?customerID", m_CustomerID)
If m_CustomerID contains the text
Haha I'm stealing your data; drop table whatever;
Then it won't end up being executed on the server as such. The AddWithValue sorts that out for you.
As for the actual executed query, you should be able to get that from the query-log, if it's enabled.
You would have to build it yourself.
Parameters are not just plopped into a string and then run as a SQL statement. The RDBMS will actually prepare the SQL and then use the parameter values as needed. Therefore, there's not a single SQL statement going to the server. To see what the SQL would be, you would have to do:
Console.WriteLine("REPLACE INTO `customer` VALUES('" & m_CustomerID & _
"', '" & m_FirstName & "', '" & m_LastName & "')")
I have the same need.
From what I've read, the query text isn't combined with the param values in the client - they are sent to the server for that.
To inspect what query was actually being sent to the server, I used mysqld logging. For my version of MySQL, I added this entry to the my.cnf:
log=queries.txt
Then, I was able to see clearly the effect of combining command text with parameters: in my case, after restarting the mysqld, I ran my unit tests and then opened the queries.txt file.
HTH!
If you want to manage logging yourself from the .NET application, your best bet is to continue using the MySqlCommand class with parameters to avoid SQL injection; however, when you log the CommandText, loop through the Parameters collection and log each one by name/type/value.