Quantcast
Channel: MySQL Forums - Connector/NET and C#, Mono, .Net
Viewing all 1447 articles
Browse latest View live

MySQLConnection StateChange (1 reply)

$
0
0
Hi,

I'm using MySql.Data.dll 6.9.8.0 to connect to a DB in C#, something like this:

(private fields)
MySqlConnection _conn;
static string _connStr;

(in a method)
_connStr = "bladibla"; //correct string of course
_conn = new MySqlConnection(_connStr);
_conn.StateChange += CheckConnection;
_conn.Open();

When the connection is "Connecting" or "Open", the StateChange event is triggered.

But when I stop the MySQL server, I don't get any event for the state change. While the connection must be either broker or closed.

Is this a known issue? Or should I take care of this in another way? Google wasn't helpful with this specific issue.
kind regards,

Matthijs

INSERT using parameters, what about datatypes? (1 reply)

$
0
0
When creating a parameter e.g. to be used in an INSERT statement, the short version is to just specify the parameterName and an value-object e.g.

DBCMD.Parameters.AddWithValue("@date", MyDateOject)

But can I trust the .Net MySQL connector will correctly convert the data saved in the MyDataObject to the right MySqlDbType used in the target table field?

Lets say MyDateOject have a value of .Net DateTime and the target field is MySqlDbType.Date (have no time)....will that work?

And will boolean be converted correctly if target field is MySqlDbType.Bit(1)

I know I can construct the parameter setting the MySqlDbType explicit but if I can trust the "automatic" conversion that would be the easiest way.

CommandTimeout for ExecuteNonQuery seems to be duplicated (no replies)

$
0
0
Hello everybody,

I am new on this forum. I have an issue on MySQL commands timeout.
My configuration is:
- MySQL server 5.6.23
- .NET 4.0
- Connector C#
- MySQL.Data.dll 6.9.5.0

The problem is: I would like to set a specific command timeout to launch long running stored procedure. I tried both to set it directly the property of the MySQLCommand object and to set it in the connection string, but the connection seems to fail after the double of the number of seconds I configure. I mean: if I set 10 seconds the DB call fails after 20 seconds, if is set 5, it fails after 10 seconds, and so on.

Am I missing something? Thanks for any help.

Dario



This is the code which resumes my tests:

1/3) C# CODE:
---------------------------------------------------------------
DateTime dtStart, dtEnd;

MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["tdm_local"].ConnectionString);
connection.Open();

// Create sql command
using (MySqlCommand sqlCommand = new MySqlCommand("Infinity", connection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;

Console.WriteLine("Connection Timeout: {0}; Command Timeout = {1}", sqlCommand.Connection.ConnectionTimeout, sqlCommand.CommandTimeout);

// set parameters
sqlCommand.Parameters.Clear();

dtStart = DateTime.Now;
try
{
sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
dtEnd = DateTime.Now;
Console.WriteLine("Inner time: {0}", (dtEnd - dtStart).TotalSeconds);
}
}

connection.Close();
connection.Dispose();
----------------------------------------------------


2/3) CONNECTION STRING
----------------------------------------------------
<add name="tdm_local" connectionString="server=localhost;user id=youruser;password=yourpassword;database=yourdatabase;pooling=true;default command timeout=5;" />


3/3) DB LONG RUNNING STORED PROCEDURE
----------------------------------------------------

DROP procedure IF EXISTS `Infinity`;

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `Infinity`(

)
BEGIN

select sleep(900);

END$$

DELIMITER ;

Can't Bulk Load CSV with blank fields (no replies)

$
0
0
In attempting to use the MySQLBulkloader in a Visual Studio program I have come across a problem when attempting to load (large CSV) files that use blank fields (,,) to indicate Null values. In would prefer not to have to preprocess these large text files to inject the word NULL where appropriate just to accomplish what should be a basic task.

I understand that converting a blank field to 0 or "" is not a bug in the LOAD DATA INFILE command but nevertheless it is not what I need it to do and there is no simple "switch" to make it behave the way I need. I was wanting to use the columns and SET feature of the LOAD DATA INFILE to accomplish the blank to Null conversion on the fly but have hit the following problems:

1) For the MySQLBulkloader class the Columns and Expressions properties are both read only - so I can't use that. Actually I'm not really sure what the point of these properties is if they are read only.

2) I've also tried to manually code the full LOAD DATA INFILE command into the MySQLCommand using the Query:

LOAD DATA INFILE 'myfile.csv' INTO TABLE MyTable
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(@Var1,@Var2)
SET Column1 = NULLIF(@Var1,''), Column2 = NULLIF(@Var2,'')

But unfortunately the MySQLCommand class realises that @Var1 and @Var2 are parameters and does not pass the SQL through literally to the server. Obviously I don't want to "set" there parameters as that would change the logic of the SQL.

So how can I accomplish my task?

'Windows-1252' is not a supported encoding name. (1 reply)

$
0
0
O erro está no seu banco de dados, caso tenha algum campo com valor NULL adicione algum valor ou exclua-o.

também pode ser corrigido na hora de criar sua tabela, eu corrigi o meu erro com esse código na hora de criar a tabela no mysql.

Create table app (
ID Int UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
login Varchar(30),
senha Varchar(40),
Primary Key (ID)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci;


O destaque vai para esse codigo.

Primary Key (ID)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci;

ON DUPLICATE KEY UPDATE - Same Query Different Results (no replies)

$
0
0
In my test app; Successive execution of the following query always returns positive row count, even when there is no change.

insert into test (k,v) values ('testkey',123)
on duplicate key update v=values(v);

The query works as expected in MySQL Console and MySQL Workbench. I get 1 for the first insert and 0 for the successive calls.

However when I try in my C# test app I always get 2 even when nothing changes inside the row.

Any ideas? Am I missing something while setting up the connection?

This is my test table:

CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`k` varchar(45) DEFAULT NULL,
`v` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `icol_UNIQUE` (`k`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;


And this is my tiny test code:

using (var con = new MySqlConnection("Database=mydb;Data Source=localhost;User Id=root;Password=mypass;CharSet=utf8;"))
{
con.Open();
var cmd = new MySqlCommand("insert into test (k,v) values ('testkey',123) on duplicate key update v=values(v)", con);
var rows = cmd.ExecuteNonQuery();

Console.WriteLine(rows); // rows is always 2
}

NOTES:

- I am using MySql .Net Connector 6.9.8
- All database charset/collation settings are utf8

C# no results unlike workbench (no replies)

$
0
0
Hi All,

When i run the following SPROC from workbench 6.3 CE i get my expected results however my C# code always reruns empty. I tried different ways to pass in datetime values without success. please help!

SPROC:
CREATE DEFINER=`sa`@`%` PROCEDURE `HistorySearch`(
IN BeginTime datetime,
IN EndTime datetime
)
BEGIN

set @qry = CONCAT('select distinct ID from History where TimeStamp >= ','''',@BeginTime,'''',' and TimeStamp <= ','''',@EndTime,'''');

PREPARE stmt1 FROM @qry;

EXECUTE stmt1;

DEALLOCATE PREPARE stmt1;
END


If I execute this SPROC from workbech as:

set @BeginTime = '2015-03-03 22:42:51';
set @EndTime = '2017-03-03 22:42:51';
call DB1.HistorySearch(@BeginTime, @EndTime);
SELECT @BeginTime, @EndTime;

I get good results.

However i get no results from C#:

try
{
if (_mySqlConnection != null)
{
var cmd = new MySqlCommand
{
Connection = _mySqlConnection,
CommandText = spHistorySearch,
CommandType = CommandType.StoredProcedure
};

cmd.Parameters.AddWithValue("@BeginTime", "2015-03-03 22:42:51");
cmd.Parameters.AddWithValue("@EndTime", "2017-03-03 22:42:51");

MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
rdr.Close();
}
}
catch (MySqlException ex)
{
;
}

I'm using connector Net 6.9.8.

Thank you,
Sa'Ed

Entity Framework 7 support - EF7 (no replies)


Mono 4.x support (no replies)

$
0
0
Hi all,

Just a quick question: I would like to understand if Connector/Net supports Mono 4.x. If so, any known issues? If not, is this support planned?

Thank you,
Chris.

MySql Exception by Selecting Auto_Increment Values C# (no replies)

$
0
0
0
down vote
favorite
I want to get the username and userid, but when i executing the command I get the Exception:

Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: startIndex"
The Database has the Items: UserID(AutoIncrement Int(9)(PK)) and UserName(Varchar(20))

Code:

using (MySqlConnection connection = new MySqlConnection(DBConnection.ConnectionString))
{
connection.Open();
MySqlCommand getUser = new MySqlCommand("SELECT * FROM User Where UserID = '42'", connection);
MySqlDataReader reader = getUser.ExecuteReader();
if (reader.HasRows){
The Exception is thrown at "ExecuteReader".
Queue

"Select* From User Where UserID ='42'" is Executing without any trouble on the Server.

I also tried only the query

SELECT * FROM User Where User
But I get the same exception.

I can insert into the Table and I can get the Last insert ID but when I try to every Database with Select * From XY I get the same Exception. All the Tables are with innobDB and the all have at least 1 primary or foreign key.

If I only select the UserName the Query is working:

Select UserName From User

But when I try to get the UserID

Select UserID From User

I get the Exception:

{"Destination array is not long enough to copy all the items in the collection. Check array index and length."} System.Exception {System.ArgumentException}

connecting to mysql from VB (no replies)

$
0
0
Hi

Mysql community is installed and working fine with workbenck. Then created a project using VB community 15, have first added mysql.data.dll v6.9.8 , then this line to the project - Imports MySql.Data.MySqlClient

However when I come to connect to a database I can not see mysql in choose data source window!

searching the net found that I have to use V 6.6.7 connector NOT V 6.9.8

I ve uninstalled that version and installed V 6.6.7 but still can Not find mysql in VB chosse data source window!

Any help please?

MySqlAdapter & .Net 3.5 (no replies)

$
0
0
My program DataAdapter & Fill are not working, can MySqlDataAdapter be used with framework 3.5? This worked before in framework 2.0, but I don’t appear to be retrieving any data now. Here is the code used. The sql is working as I have used it in MySql workbench and it pulls the data.

string strSQL;

string strWhereAnd;

MySqlCommand objCmd;

MYSQL_DB objMYSQLDB;

MySqlConnection objMySqlConnection = null;

objMYSQLDB = new MYSQL_DB();

objMySqlConnection = objMYSQLDB.GetMySqlConnection();

objCmd = new MySqlCommand();

objCmd.CommandType = System.Data.CommandType.Text;

objCmd.Connection = objMySqlConnection;


System.Data.DataSet ds;

MySqlDataAdapter da;


ds = new System.Data.DataSet();

da = new MySqlDataAdapter(strSQL, objMySqlConnection); //'### Retrieve Data in to DataAdapter ....

objCmd.CommandText = strSQL;

da.SelectCommand = objCmd;

da.Fill(ds, "TBL1");

//### Fill DataSet from DataAdapter ....

return ds;

MySQL Connector/NET: X DevAPI Reference (no replies)

SQL Server / ADO / C++ Conversion (no replies)

$
0
0
Let first apologize if this is not in the right location. I was unsure where to go so "Newbie" caught my eye. I am in the process of converting Visual C++ code using ADO to access a SQL Server database over to MySQL. Using the MySQL Provider (Cherry City Software), it appears I am able to connect. However, I am running into issues executing SP's as our legacy code attempts to handle the SP output using ADO Streams. Is anyone aware of a MySQL access provider that supports streaming output and supports C++? I am concerned I may be better served rewriting our C++ data access layer and moving away from ADO when connecting to MySQL. Thanks for any thoughts!

Cannot establish ssl connection (no replies)

$
0
0
Hello

I'm a beginner but I've made a Powershell script that uses the mysql connector/net and it works. But now I would like to move the connection to a ssl connection. I followed the steps to first make certificate files. I used a Linux host to generate the files, as explained on:
http://dev.mysql.com/doc/mysql-security-excerpt/5.0/en/creating-ssl-files-using-openssl.html
I had no cacert.pem file so I downloaded it there:
http://curl.haxx.se/ca/cacert.pem
I also created a client.pfx file from those files, since .NET requires it, as explained on:
https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-ssl.html

Finally I moved the certificate files on my Windows host with the working mysql server. I added those lines in my.ini:
[mysqld]
ssl-ca="C:\\Share\\OpenSSL\\cacert.pem"
ssl-cert="C:\\Share\\OpenSSL\\server-cert.pem"
ssl-key="C:\\Share\\OpenSSL\\server-key.pem"
(others ssl variables where empty)

I loaded mysqld with --log-error-verbosity=3 to catch everything that go wrong.
I used phpmyadmin in "variables" section to show ssl variables and to be sure that files are loaded and that SSL is active. Variables were set:
have ssl = yes
ssl ca = C:\Share\OpenSSL\cacert.pem
ssl cert = C:\Share\OpenSSL\server-cert.pem
ssl key = C:\Share\OpenSSL\server-key.pem

Then I created a user named ssluser with require_ssl on on it. Now, I do this in Powershell:

[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$connection.ConnectionString = "Server=localhost;Uid=me;Pwd=somepass;database=p4-projet;"

Then: $connection.open()
Which works good (connection state is open with no errors). But now when I try with ssl:

$connection.ConnectionString = "Server=localhost;Uid=ssluser;Pwd=somepass;database=p4-projet;CertificateFile=C:\Share\OpenSSL\client.pfx;CertificatePassword=pass;SslMode=Required"
"pass" is the password I used while making the pfx.

Then: $connection.open()
Gives this error:
---
Exception calling "Open" with "0" argument(s): "Received an unexpected EOF or 0 bytes from the transport stream."
At line:1 char:1
+ $connection.open()
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IOException
---

I searched and found the same error in different languages that use the same method. One mentionned that it could be the different hostname between the machine and the one in the certificate. I tried with my machine name but it still give the error. Could it be because I generated the files on Linux and using them on Windows? Or am I missing something in the parameters or in the mysql configuration? The error log doesn't show something about this, even with verbosity set to 3.

Specifying an empty geometry collection (no replies)

$
0
0
Hi,

I am wondering if you can help me clarify how to create a MySqlGeometry instance that represents and writes an *empty* geometry collection to the MySQL 5.7 database? I am using MySql.Data 6.9.8.

Thanks,
Andreas

My application freeze when loading information from my database (no replies)

$
0
0
Hello, i have a annoying bug when i try to reach the database server, my application freeze.

I have searched and come down with the background worker and i done it but it keeps freezing for a couple seconds.

You have a great help voor me earlier so i hope that you guys can help me.

private readonly BackgroundWorker worker = new BackgroundWorker();


private void Window_Loaded(object sender, RoutedEventArgs e)
{
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.RunWorkerAsync();
}

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
Dispatcher.Invoke(new Action(() =>
{
conn4.Open();
MySqlCommand cmd = new MySqlCommand("Select ID,Voornaam,Achternaam,Gebruikersnaam,Wachtwoord,Email,Taal from Gebruikers", conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "LoadDataBinding");
dataGridCustomers.DataContext = ds;
conn4.Close();
label.Content = dataGridCustomers.Items.Count - (1);
int number = Convert.ToInt32(label.Content);
number = number + 1;
label.Content = number.ToString();
}));
}

private void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
//checking for username and email
}

Sorry for my bad english.

Greetings from the Netherlands.

Which is correct DLL for using MySqlClient (no replies)

$
0
0
I keep getting this error -
The type 'MySql.Data.MySqlClient.MySqlConnection' exists in both 'c:\Users\Upendra\Documents\Visual Studio 2010\Projects\CrosswordMVC\packages\MySQL.NET.6.6.4\lib\net20\MySql.Data.dll' and 'c:\Users\Upendra\Documents\Visual Studio 2010\Projects\CrosswordMVC\packages\MySQL.NET.6.6.4\lib\net20\MySql.Data.CF.dll' C:\Users\Upendra\documents\visual studio 2010\Projects\MySqlMVC\MySqlMVC\Models\BusinessLayer.cs 26 17 MySqlMVC

Which is the correct library to use ?
I had added references to the following only
MySql.Data
MySql.Data.Entity
MySql.Web

Somehow the MySql.Data.CF gets added - is this through the MySql Connector/NET ?
In this case-
how do I reference the MySqlClient class ?
I know one solution is to use fully qualified namespaces, but more importatnt question I need answered is which fully qualified namespace one should I use ?

Error calling Stored Procedure - Can not return a result (no replies)

$
0
0
Hi,

I'm calling a stored procedure named SPComportamentoCompra and happens this error:

MySQLDriverCS Exception: MySQLDriverCS Error: wrong query.PROCEDURE dbo.SPComportamentoCompra can not return a result set in the given context CALL SPComportamentoCompra (8 'WPComportamentoCompras', 1, '21.11.2015', '5/19/2016' , 'V' 0, 'T', '4')

Does anyone know what is generating the error?

Any idea how to solve this?

Thank you!

.NET Async operation performance problems (no replies)

$
0
0
If I have a code that ExecuteNonQuery or ExecuteReader or ExecuteScalar they work just ok and the performance is... well, quite ok. Now, if I wan't to not eat up not so much resources, I run the async versions, ExecuteNonQueryAsync or ExecuteReaderAsync or ExecuteScalarAsync and I expect the business logic thread to be non-blocked while SQL is executing. For technical background details see: http://fsprojects.github.io/SQLProvider/core/async.html

Anyways, this is the expected result. Actual result is that if I run this with 10 of threads (like web servers usually do), not only the threads are not locked ( http://stackoverflow.com/questions/30551459/mysql-c-sharp-async-methods-doesnt-work ), but the whole server is jammed and I got SQL-deadlocks and everything.

Here is the sample source code in F#:
let cstr = "server = localhost; database = TestDB; uid = root;pwd = 12345"

let ExecuteSqlOld (query : string) parameters =
    use rawSqlConnection = new MySqlConnection(cstr)
    rawSqlConnection.Open() 
    use command = new MySqlCommand(query, rawSqlConnection)
    parameters |> List.iter(fun (par:string*string) -> command.Parameters.AddWithValue(par) |> ignore)
    let affectedRows = command.ExecuteNonQuery()
    ()

let ExecuteSql (query : string) parameters =
  async {
    use rawSqlConnection = new MySqlConnection(cstr)
    do! rawSqlConnection.OpenAsync() |> Async.AwaitTask
    use command = new MySqlCommand(query, rawSqlConnection)
    parameters |> List.iter(fun (par:string*string) -> command.Parameters.AddWithValue(par) |> ignore)
    let! affectedRows = command.ExecuteNonQueryAsync() |> Async.AwaitTask
    ()
  }

The problem is also reproducable with the source code in this repo, under Thread test, changing the last method to use SubmitUpdatesAsync:
https://github.com/fsprojects/SQLProvider/blob/master/tests/SqlProvider.Tests/scripts/MySqlTests.fsx
Viewing all 1447 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>