C# Mysql Query Execution [duplicate] - c#

I simply want to execute the following Mysql statement
SET #a = 1;SELECT #a;
with MySql.Data.MySqlClient
[System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$password = 'mypassword'
$sql = "SET #a = 1;SELECT #a;"
$server = 'localhost'
$port = 3306
$database = 'test'
$User = 'root'
$conn=new-object MySql.Data.MySqlClient.MySqlConnection
$connectionstring = "Server=$Server;Port=$port;Database=$DataBase;Uid=$User;Pwd=$Password;allow zero datetime=yes"
$conn.ConnectionString = $connectionstring
$conn.Open()
$cmd=new-object MySql.Data.MySqlClient.MySqlCommand($sql,$conn)
$ds=New-Object system.Data.DataSet
$da=New-Object MySql.Data.MySqlClient.MySqlDataAdapter($cmd)
$da.fill($ds)
$conn.close()
$ds.tables[0]
I get a fatal error.
When I replace $sql by either
$sql = "SELECT DATABASE();"
or
$sql = "SELECT 1;"
I get the expected result.
I found this question, but it doesn't solve my problem.
I'm trying to port SQLIse (a part of the SQLPSX project ) to the MySQL version MySQLIse.
I want to process any simple valid mysql statements.
EDIT:
I was trying to run parts of the sakila-schema.sql the mysql demo database install script which runs by something like
mysql> SOURCE
C:/temp/sakila-db/sakila-schema.sql;

I found the solution in this blog
I have to add
;Allow User Variables=True
to the connection string:
$connectionstring = "Server=$Server;Port=$port;Database=$DataBase;Uid=$User;Pwd=$Password;allow zero datetime=yes;Allow User Variables=True"
works. I tested it with version 6.3.6.0. of MySql.Data.

Related

Postgres parameters at SQL requests, C#

I run these commands in a Windows Forms app written in C#:
NpgsqlCommand command = new NpgsqlCommand("DO $$ BEGIN IF EXISTS(select id from clients where id=#cnumberclient) THEN INSERT INTO reservations(roomnumber,clientnumber,datein, dateout) values(#rnumber, #cnumber, #din, #dout); ELSE raise notice 'HYI'; END IF; END $$;", conn.getConnection());
command.Parameters.Add("#cnumber", NpgsqlDbType.Integer).Value = ClientId;
command.Parameters.Add("#cnumberclient", NpgsqlDbType.Integer).Value = ClientId;
command.Parameters.Add("#rnumber", NpgsqlDbType.Integer).Value = RoomId;
command.Parameters.Add("#din", NpgsqlDbType.Date).Value = dateIn;
command.Parameters.Add("#dout", NpgsqlDbType.Date).Value = dateOut;
then I open the connection and execute the command:
conn.openConnection();
if (command.ExecuteNonQuery() == 1)
But I get an error.
column "cnumberclient" doesn't exist
Postgres doesn't seem to see the parameters
Can you help me?
Remove the # symbol from your parameters, that's not part of the parameter name, it's the symbol to identify them in the Sql query.

Trying to insert a proper string value in parameterized query using Odbc and MySQL results in empty string in database

I'm trying to use parameterized queries in C# for my job assignment as it seems to be the correct way to guard against SQL injections and simplify code.
When the INSERT command is executed the row is inserted otherwise correctly except the string/varchar column is empty.
I attached the minimum code necessary below. Database column types are as follows:
id_number = int(11), datetime_now = datetime, some_text = varchar(64).
The code is running on Ubuntu 14.04.6 LTS and connecting to local database MySQL 15.1 Distrib 5.5.64-MariaDB. The driver is /usr/lib/x86_64-linux-gnu/odbc/libmyodbc.so.
I could only find one example online of this exact problem (no answers):
String Parameters not working when using MySql over Odbc
I've been stuck with this for a couple of days now and I'm getting desperate. I don't know how to proceed except abandoning parameterized queries completely. I've tried different overloads of the OdbcParameterCollection.Add() method as well as AddWithValue(), still the results are incorrect. Is it possible there is a problem with the ODBC driver itself?
OdbcCommand command = conn.CreateCommand();
command.CommandText = "INSERT INTO MyTable (id_number, datetime_now, some_text) VALUES (?, UTC_TIMESTAMP(), ?)";
command.Parameters.Add("#id_number", OdbcType.Int).Value = 1;
command.Parameters.Add("#some_text", OdbcType.VarChar).Value = "Example text";
conn.Open();
command.ExecuteNonQuery();
I would expect that the row would be inserted correctly or an error would be given.
Instead the inserted row has
id_number = 1, datetime_now = 2019-08-22 14:05:19, some_text = "".
Edit. Changed code: added "#" to parameter names to exactly follow accepted answers in: How to bind parameters via ODBC C#?. The problem still persists.
Edit2. Added datatable code and information about the connection string.
Database table code is:
MariaDB [myDB]> SHOW CREATE TABLE MyTable;
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| MyTable | CREATE TABLE `MyTable` (
`id_number` int(11) NOT NULL AUTO_INCREMENT,
`datetime_now` datetime NOT NULL,
`some_text` varchar(64) NOT NULL,
PRIMARY KEY (`id_number`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
The connection string uses DSN, so it is:
connString = "DSN=myodbc-mydb;";
/etc/odbc.ini:
[myodbc-mydb]
Driver = myodbc_mysql
Description = myODBC
SERVER = 192.168.24.25
PORT = 53769
USER = myUser
Password = myPassword
Database = myDB
OPTION = 3
SOCKET =
/etc/odbcinst.ini:
[myodbc_mysql]
Description = ODBC for MySQL
Driver = /usr/lib/x86_64-linux-gnu/odbc/libmyodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libodbcmyS.so
UsageCount = 8
Threading = 0

How to update from C# to SQL Server

I've calculated my 'ERna', and now I want to update it to my SQL Server database. I've made the statement, but I don't quite get how I get it to update in my database from C#.
Any ideas?
decimal ERna = ERnu - bprijs;
lbEigenRisico.Content = ERna;
string updateQuery = "UPDATE Verzekering SET eigen_risico = #ERna";
SqlCommand command = new SqlCommand(updateQuery, dbconn.Connection);
command.Parameters.AddWithValue("#ERna", ERna);
You just need to open the connection and call command.ExecuteNonQuery()

Ms Access password Storage

I am using MS Access as a database for a school project. The following is my query:
public static string qry4 = "update INTERNETSETTINGS set password = #password , url = #url , databasename = #databasename , port = #port , username = #username";
It is giving me the following error: Syntax Error in Update Statement
Command.Parameters.AddWithValue("#url", urlBox.Text.ToString());
Command.Parameters.AddWithValue("#databasename", databaseBox.Text.ToString());
Command.Parameters.AddWithValue("#port", portBox.Text.ToString());
Command.Parameters.AddWithValue("#username", userBox.Text.ToString());
Command.Parameters.AddWithValue("#password", passwordBox.Text.ToString());
It is making me angry because every thing is ok and right on target but still I am getting the error, but when I remove password from query it works fine. Please Help.
Most likely, password is a reserved keyword. Place it in braces...
update INTERNETSETTINGS set [password] = #password...

C# Prepared Statements - # sign (at / strudel sign) queries

I Have a problem with a prepared statement in C#:
OdbcCommand cmd = sql.CreateCommand();
cmd.CommandText = "SELECT UNIQUE_ID FROM userdetails WHERE USER_ID = ?";
cmd.Parameters.Add("#USER_ID", OdbcType.VarChar, 250).Value = email;
(of course email contains a valid email address, with # sign).
This code returns a random error -
"The connection has been disabled"
{"ERROR [01000] [Microsoft][ODBC SQL
Server Driver][TCP/IP
Sockets]ConnectionWrite (send()).
ERROR [08S01] [Microsoft][ODBC SQL
Server Driver][TCP/IP Sockets]General
network error. Check your network
documentation."}
However if I run my code without a prepared statement, meaning:
cmd.CommandText = "SELECT UNIQUE_ID FROM userdetails WHERE USER_ID = '"+email+"'";
Everything works perfectly.
Maybe it's related to the fact that I have a # sign in the parametrized value? I tend to think I'm not the first one trying to create a prepared statement with an email address...
I have no idea what's wrong! Other prepared statements work normally...
Can you please help? :)
Thanks,
Nili
Indeed, ODBC has its share of issues with supporting named parameters.
However, certain usage of named parameters is possible.
For example, in your case the following syntax works:
OdbcCommand cmd = sql.CreateCommand();
cmd.CommandText = "SELECT UNIQUE_ID FROM userdetails WHERE USER_ID = ?";
cmd.Parameters.Add("USER_ID", OdbcType.VarChar, 250).Value = email;
More tricky situation is when you don't have a unique match for the parameter like USER_ID = ?; e.g., when you want to use the IN operator in the WHERE clause.
Then the following syntax would do the job:
OdbcCommand cmd = sql.CreateCommand();
cmd.CommandText = "SELECT UNIQUE_ID FROM userdetails WHERE USER_ID IN (?, ?)";
cmd.Parameters.Add("?ID1", OdbcType.VarChar, 250).Value = email1;
cmd.Parameters.Add("?ID2", OdbcType.VarChar, 250).Value = email2;
Please note the usage of ? (question mark) instead of # (at sign) within the parameter name. Although note that substitution of parameters' values in this case has nothing to do with their names, but only with their order with the parameters collection.
I hope this helps :-)
Use '#USER_ID' instead of '?' and all should work:
OdbcCommand cmd = sql.CreateCommand();
cmd.CommandText = "SELECT UNIQUE_ID FROM userdetails WHERE USER_ID = #USER_ID";
cmd.Parameters.Add("#USER_ID", OdbcType.VarChar, 250).Value = email;
Is there a specific reason you're using OdbcCommand rather than using the SqlClient provider?
With the SqlClient provider, you should be using named parameters as others have suggested.
But according to MSDN:
The .NET Framework Data Provider for OLE DB and .NET Framework Data Provider for ODBC do not support named parameters for passing parameters to an SQL statement or a stored procedure. In this case, you must use the question mark (?) placeholder, as in the following example.
So I'm not sure named parameters will work in this case.

Categories