Error connecting to mySQL database from C# application - c#

I'm trying to connect to a mySQL database from C# application but getting the following error.
Keyword not supported: 'database'.
The mySQL.Net connector version is 6.9.6
Following is the connection string in my app.config file.
<connectionStrings>
<add name="ABC.DAL.CONN.MySql" providerName="DataProvider.MySql" connectionString="SERVER =MyServer; database =my_database; UID =admin; Pwd =Dba49!;"/>
</connectionStrings>
Following is the piece of code that connects to MySQL database for bulkinsert -
MySqlConnection mySqlConn = new MySqlConnection(dbConnString);
MySqlBulkLoader obSBC = new MySqlBulkLoader(mySqlConn);
obSBC.Columns.Add("CUSTOMER_ID");
obSBC.Columns.Add("VEHICLE_NUMBER");
obSBC.TableName = "TX_CUSTOMER";
obSBC.FieldTerminator = #",";
obSBC.FileName = strFilePath + strFileName;
obSBC.NumberOfLinesToSkip = 0;
obSBC.Priority = MySqlBulkLoaderPriority.None;
obSBC.Timeout = 2000;
obSBC.ConflictOption = MySqlBulkLoaderConflictOption.None;
int countRecords = obSBC.Load();
I checked a lot of forums but unable to resolve the error.

There is an old bug in MySQL that under certain conditions makes connection strings case sensitive. AFAIK I know this has never been fixed.
Please try deleting all the whitespaces from your connection string and write the keyword Database (and it's value, if that is in Caps too) in Caps.

Related

SQLite connection string: 'Version' keyword is not supported in C#

I have a c# winform project that supposes to save data to SQLite database, I've already used the dll properly and it runs without error, but I get an exception when trigger the method with buttonClick event
here the exception i got : Keyword not supported :'version'.
this the connection string:
"Data Source = Diary.db;Version = 3;New = False;Compress = True;";
and this the complete method :
private void AddToDbaseSQL3()
{
try{
string query = "insert into Diary(title,date,mood,wheater,content)
values('"+TitleTextbox.Text+"','"
+dateTimePicker.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','"
+MoodCombobox.SelectedItem+"','"
+WheaterCombobox.SelectedItem+"','"
+ContentTextbox.Text+"');";;
SqlConnection connect2 = new SqlConnection(connection2);
SqlCommand cmd = new SqlCommand(query,connect2);
SqlDataReader read;
connect2.Open();
read = cmd.ExecuteReader();
while(read.Read())
{
}
MessageBox.Show("created");
TitleTextbox.Text = "Title";
TitleTextbox.ForeColor = SystemColors.ControlLight;
ContentTextbox.Clear();
connect2.Close();
}catch(Exception e){
MessageBox.Show(e.Message);
}
}
I've looked to this link:
Keyword not supported: 'version'
and it said to change SqlConnection to SQLiteConnection but it ended with an error, can you tell what's is the right connection string ? or there is something wrong from my code/method? please tell me, thank you, I'm sorry because it's my first time using the SQLite
SqlConnection from System.Data.SqlClient is for SQL Server.
You need an dedicated SQLite ADO.NET provider.
You can found the System.Data.SQLite provider from SQLite team here:
https://system.data.sqlite.org
Or you can use any libre or commercial provider.
You can also use the free and open-source SQLite ODBC driver that works fine and allow to use VS Visual Designers to create strongly typed ADO.NET DataSets, in addition to the use of OdbcConnection, OdbcCommand and so on:
http://www.ch-werner.de/sqliteodbc
C# Reading data from existing SQLite database

Not inserting data into database and not getting any error

I am not sure what I am doing wrong, If I use the connection string shown here, my application works fine.
SqlConnection conn = new SqlConnection();
string DbPath = Application.StartupPath;
DbPath = DbPath.Substring(0, DbPath.LastIndexOf("\\bin"));
DbPath = DbPath + "\\MyDatabase.mdf";
conn.ConnectionString = "Data Source=.\\EXPRESS2008;AttachDbFilename=" + DbPath + ";Integrated Security=True;User Instance=True";
but if I use connection string here, it's not inserting data into MyDatabase table
conn.ConnectionString = Properties.Settings.Default.MyDatabaseConnectionString;
My app.config is
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="ERPSystem.Properties.Settings.MyDatabaseConnectionString"
connectionString="Data Source=.\EXPRESS2008; AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated
Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
INSERT statement and preceding code:
comm = new SqlCommand("CreateUser", MyConnection.MyConn("Open"));
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("#UserName", SqlDbType.VarChar).Value = userName.Text;
comm.Parameters.Add("#Password", SqlDbType.VarChar).Value = userPassword.Text;
comm.Parameters.Add("#UserRole", SqlDbType.VarChar).Value = UserRole.SelectedItem.ToString();
comm.ExecuteNonQuery();
This is the code to get the connection
class MyConnection
{
public static SqlConnection MyConn(string str)
{
SqlConnection conn = new SqlConnection();
try
{
//get application path
string DbPath = Application.StartupPath;
if (Program.RunFrEn == true) //bool var
//remove string after bin folder
DbPath = DbPath.Substring(0, DbPath.LastIndexOf("\\bin"));
//add database name with new path
DbPath = DbPath + "\\MyDatabase.mdf";
//generate new connection string for database
conn.ConnectionString = "Data Source=.\\EXPRESS2008;AttachDbFilename="
+ DbPath
+ ";Integrated Security=True;User Instance=True";
//conn.ConnectionString = Properties.Settings.Default.MyDatabaseConnectionString;
if (str == "Open")
{
if (conn.State == ConnectionState.Closed)
conn.Open();
}
else
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return conn;
}
}
I am not getting any error
Thank you
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
I also had fighted long time with same problem. And I saw many same questions & answers.
You're using |DataDirectory|. I assume you can get values from the DB file and you don't get error to run insert command but the values are not inserted into the DB file.
This is absolutely my private idea and my private conclusion is that this behavior is normal as |DataDirectory| does. I mean a data file of an application should be protected from manipulation once after deployment. The 'Data' file should provide data inside the file so that we can read the data.
Therefore, I coded to create a localDB .MDF file (SQL Server 2014) from users' side so that my applications can utilize the localDB to write and read data. My application automatically downloads data from cloud server which are we need to update frequently. On the other side, I put big and already fixed data into |DataDirectory| .MDF file, I mean inserted big data for read only and add the .MDF file to my project before deployment.
Hope my experience helps.. But, please keep in mind again that this is really my private opinion and I might be totally wrong and my experience is limited only to localDB. But again, I couldn't find a Microsoft's official document mentioning this behavior.
Do you have only 1 option like |DataDirectory|? Did this work to insert before? Is this code by you wrote on your own? If possible, try to find another option rather than |DataDirectory| to connect to the SQL Server database. I use a cloud SQL server with IP address but I can't understand why you use |DataDirectory|. There might be many various options as connection strings to SQL Server Express.

C# Oracle Connection with MSDAORA.1

I have a Excel-Sheet connected with a Oracle Database with MSDAORA.
Connection String in Excel is
Provider=MSDAORA.1;User ID=xxx;Password=xxx;Data Source=yyy.com
CommandType is Tabledirect and CommandText is "zzzzzz"."ZZZZZZZZ"
Integrated Security is Windows Authentication
So i createt a small Test App for connecting me to the Oracle-DB with C#.
It seems the Connection String is the same, but its not working.
Error Message : OLEDB Exception - Error executing OLEDB Procedur
Using VS2012 / NET3.5 /
tbConnectionString.Text = #"Provider=MSDAORA.1;User ID=xxx;Password=xxx;Data Source=yyy.com";
tbCommandText.Text = #"""zzzzzzz"".""ZZZZZZZZZZ""";
myOleDbConnection = new OleDbConnection(tbConnectionString.Text);
OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();
myOleDbCommand.CommandType = CommandType.TableDirect;
myOleDbCommand.CommandText = tbCommandText.Text;
myOleDbConnection.Open();
THX
Is an issue of Operating system and VS version.
Because I faced same problem before when using Win 7.
After diagnosing the issue , we find solution of Oracle.DataAccess.
Check out the support of msdaora.1.

Creating an SQL Server connection string without importing a datasource in C#

I am going off of this tutorial: http://www.dotnetperls.com/sqlclient . Instead of adding a data source and a having visual studio compile my connecting string - I want to do it myself. The reason being is that the database will not always be the same and I want this application to be able to use different databases depending on which I point it to.
So how can I manually create the connection string? I am using SQL Server 2005.
Step 1: Go to connectionstrings.com and find the proper format for your database.
Step 2: Plug in the appropriate values to the connection string.
Step 3: Pass that string to the constructor of SqlConnection.
I would also suggest storing your connection string in your app.config/web.config file. You can then modify them easily if needed. The proper format can be found at MSDN - connectionStrings element. You then change your code to:
SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnStringName"].ConnectionString);
I don't see where the connection string is "compiled".
In the code
SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString)
ConsoleApplication1.Properties.Settings.Default.masterConnectionString is a field and it can be replaced with any other appropriate string.
for SQL Server format of the connection string is
"Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = **;"
save this connection string in a string variable and use with connection object.
either way you can add in web.config file.
<ConnectionString>
<add name = "name_of_connecctionString" ConnectionString = "Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = ****;" ProviderName = "system.Data.SqlClient"/>
</ConnectionString>
you can change the provider as needed by you.
then in code behind file access this particular connection string using configuration manager.

C# MySql connection cannot find host

I have a java program that connects to a MySql database and it's working fine.
Now I want to convert it to a C# program, but I keep getting the error "Unable to connect to any of the specified hosts".
I've already followed the following solutions:
Connect to MySql with C#
C# MySqlConnector
Configure the ODBC DNS
And the reference to MySql.Data has been added to the project.
Here is the code to connect to the database:
string connectionString = string.Format(
"SERVER={0}; DATABASE={1}; UID={2}; PASSWORD={3};",
"jdbc:mysql://" + host + ":" + port, dbName, userName, password);
// Prepare connecting to the database.
myConn = new MySqlConnection(connectionString);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = #"SELECT * FROM table_name";
myConn.Open(); // <- MySqlException: Unable to connect to any of the specified MySQL hosts.
MySqlDataReader reader = command.ExecuteReader();
List<string> exampleStore = new List<string>();
while (reader.Read())
{
// Just an example for storing data.
exampleStore.Add(reader.GetString(0));
}
The java version connects to the same server with the same values as I used here, so please don't suggest checking if the server is online.
So the problem must be in my C# code, I noticed Class.forName("com.mysql.jdbc.Driver").newInstance ();
In the java code. Seems like the driver is made active here, maybe C# needs to do something similar that I'm missing?
Edit: So the connection string should be: string connectionString = string.Format("SERVER={0}; DATABASE={1}; Port={2}; UID={3}; PASSWORD={4};", host, dbName, port, userName, password));
Was using some extra elements from the java version, din't think they would cause these problems. Thanks for the help guys.
The standard connection string is:
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;.
Please note that the port is specified separately, with Port=1234, not in the Server field. Also, eliminate jdbc:mysql: from the start of the server field, as it's specific to the JDBC driver; use a normal URI string. Nothing else should be needed.
Your connection string is wrong.
Try:
string connectionString = string.Format("SERVER={0}; DATABASE={1}; Port={2}; UID={3}; PASSWORD={4};", host, dbName, port, userName, password));

Categories