Having troubles with a correct connection string - c#

I have been looking around on the internet to find the proper connection string format, but I find different ones all over the place from different topics posted years between. I can't seem to find the right one. I am using a MySQL Database installed as a Windows Service.
Printed here is my Connection String (I removed the Port after this picture was taken and the last semicolon is there but I omitted it accidentally). But I get the following error message:
I get Error 40 from this. Anyone know the actual correct format? I feel stupid for asking haha
EDIT:
As Requested, instantiation Code for the Connection:
StringBuilder sb = new StringBuilder();
sb.Append("Data Source=MySQL;");
sb.Append("Server=" + Server + ";");
sb.Append("Database=" + Database + ";");
sb.Append("UID=" + UserID + ";");
sb.Append("PWD=" + Password + ";");
Console.WriteLine(sb.ToString());
MySqlConnection conn = new MySqlConnection(sb.ToString());
conn.Open();
return conn;

It is searching for an SQL Server, whereas you want it to connect it to a MySQL database. I guess you are using SQLConnection to connect to the database. That will not work.
You need to either use OleDBConnection or MySQLConnection object to connect to a MySQL database.

Related

Unable to load database from local server location in C# Connection String (windows application)

I'm trying to do application to access the database from local file server, but the connection string does not recognize the server location. This is a windows form application, using sqlite. Kindly help me on this one.
File server location will be like this:
\\fileserver\Testdb\maindb.db
Code used:
string server_database_path = #"\\fileserver\Testdb\maindb.db";
string connection_data = "Data Source=" + server_database_path ;
using (var conn = new SQLiteConnection(connection_data))
{
conn.Open();
SQLiteCommand insert_Rec = new SQLiteCommand(query_text, conn);
insert_Rec.ExecuteNonQuery();
conn.Close();
}
Error:
Unable to open database file
I may be wrong but I dont think that directly specifying the .db is correct. When using a normal SQL Server I would specify the instance (or just the server hosting it if it was the default instance).
So, your connection string should look something like
string connectionString = "Data Source=192.168.0.1; User ID=administrator; Password=YOURPASSWORD"
or if you are connecting the machine you are on it should be
string connectionString = "Data Source=127.0.0.1; User ID=administrator; Password=YOURPASSWORD"
You could substitute the 127.0.0.1 for \\localhost
I was confused in doing this, but by changing the slash "\" to "/" it really worked.
When i changed the slash in the path string it started to work fine and everything goes well.
Example: #"//fileserver/Testdb/maindb.db"

How to connect my app to a database

I am trying to connect my app, developed in C# with a SQL Server database.
The program is done! It's a mobile app.
My database is on C:\ProgramFiles\MyAppName\MyDatabase.sdf
My code line is:
SqlConnection conn = new SqlConnection("server =" + iP.Text +"," + port.Text + ";integrated security=false;Initial Catalog=" + DB.Text + ";User ID=" + userName.Text + ";Password=" + Pass.Text + ";Trusted_Connection=False;");
iP.Text = my IP (102.168.XXX.XXX)
port.Text = 49214 or 1433
DB.Text = "MyDatabase.sdf"
userName.Text= "sa"
pass.Text= "MyPass"
But when I try to connect it, the app says:
er.Message = "El servidor SQL Server no existe o se ha denegado el acceso.
My server name is the same that my userName?
The application was made by someone else, I did nothing. But now I have to change some things and make it better. There is no manual
Any idea? I really don't know what to do
You are using Sql Server Compact Edition (SDF file) not Sql Server.
The classes needed to connect to this kind of database are different
SqlCeConnection conn = new SqlCeConnection(......)
The classes for Sql Server cannot parse correctly your connection string and you get the mentioned error. Of course, the classes for Sql Compact Edition require a reference to the appropriate DLL
System.Data.SqlServerCe.dll
and the appropriate using statement at the beginning of your code file
using System.Data.SqlServerCe;
As last note, the connection string for a SQL CE database is simply
"Data Source = MyDatabase.sdf; Password ='<pwd>'"
doesn't seem possible to pass a specific user. See connectionstrings.com

SQL Server Express inserts doesn't work anymore

In my C# application, I do the following:
using (SqlConnection connection = new SqlConnection(connectionstr))
{
connection.Open();
SqlCommand com1 = new SqlCommand("insert into Anfangstierbestand(bestand, jahr, loginid) VALUES (" + bestand + ", " + jahr + ", " + loginid + ");", connection);
SqlCommand com2 = new SqlCommand("select * from Anfangstierbestand;", connection);
com1.Connection = connection;
int ferksum = 0;
com1.ExecuteNonQuery();
connection.Close();
connection.Open();
SqlDataReader read = com2.ExecuteReader();
while (read.Read())
{
ferksum += Convert.ToInt32(read[2]);
}
// MessageBox.Show("Fehler beim Erstellen des Tierbestandes", "Fehler"); }
MessageBox.Show(ferksum.ToString());
}
It's a simple insert to a database. I added com2 to check, if the insert works.
Unfortunately, the the value of com2 tells me, that it works, but when I go to the Server Explorer and press Execute SQL, there are no new values.
I don´t know the reason. The code above is just an example, since a few days, no insert works anymore(before, the same code works).
Does anybody know what the reason can be?
EDIT:
C#:
string connectionstr = "Data Source=.\\SQLEXPRESS;" + "AttachDbFilename=|DataDirectory|\\Datenbank\\FarmersCalc.mdf;" + "Integrated Security=True;" + "User Instance=true;";
EDIT2:
Server Explorer:
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\user\Desktop\Farmer´s Calc\Programmierung\WPF\Finanz_WPF\Finanz_WPF\Datenbank\FarmersCalc.mdf";Integrated Security=True;User Instance=True
EDIT3:
Here are the columns:
id int,
jahr int,
anzahl int,
loginid int
EDIT4:
Is it possible that it´s a problem that I opened my project with expression blend? Normally, I work with VS 2010...
EDIT5:
Even because I can not answer my question(<100 reputations) I write it here:
Shame on me. Some of you were right, it was the wrong database-file. But I´m still wondering, why this happened, because I did not change anything since a few days and before this, it worked!
Thanks to all for helping!
You're using user instances, why? Isn't it possible that the instance you're connecting to in Server Explorer is not the same as the instance where your app is inserting data? What happens when you select data from within the app, does it reflect your insert(s)? It seems to me based on your connection strings that these are two completely different MDF files - they have the same name but they are in different locations.
Is the issue implicit transactions? Do you need to issue a commit of the SQL Insert? If com2 tells you that it's there then it may only see it since it's in the context of the current SQL transaction.
You should share your connection string for both Server Explorer and your SqlConnection (connectionstr). Ensure that you setup your Server Explorer connection with User Instance=true;.
As a diagnostic,
connection.Open();
int n = com1.ExecuteNonQuery();
// log or show 'n' , the nr of rows affected
Edit, after seeing the connectionstrings:
local db files in |DataDirectory|\ are very prone to be overwritten by the next run or build command.
Make sure you set them to 'copy never' or 'copy if newer' in the VS Solution explorer.
Perhaps somewhere in the callstack above this code, someone has added a TransactionScope.
This would cause the connections to enroll automatically in the transaction, and the connections could see the data inserted via that not-yet-committed transaction. When the scope is exitted without calling scope.Complete, the transaction gets rolled back and no data is saved.

C# Error in accessing an Access Database over LAN

Here's my connection string:
sConnection = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\" + lstNet.SelectedItem.ToString() + "\SharedDocs\Documents\Debug\App_File\ggbase.mdb;Jet OLEDB:Database Password=g3n3r4l;";
lstNet is a listbox that contains all computers found in the network.
I'm assuming something else is wrong with my connection string.
According to Connection Strings website, to access a database over LAN, the following connection string format is used:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\serverName\shareName\folder\myDatabase.mdb;User Id=admin;Password=;
I'm assuming that shareName is where my Connection String fails. What is a shareName? And what are the shareNames of Windows XP and Windows Vista / 7 if, say, I placed my database in their Shared Documents / Public Files?
I've tried modifying my connection string into the following:
\C$\Users\Public\Documents\Debug\App_File\ggbase.mdb;Jet OLEDB:Database Password=g3n3r4l;";
And I still get the following error:
"Format of Initialization string does not conform to specification"
May I have some help on this, please?
EDIT: Tried accessing the database in the Public\Documents section of a Windows Vista PC on my network with the following connection string:
\Public\Documents\Debug\App_File\ggbase.mdb;Jet OLEDB:Database Password=g3n3r4l;";
I also tried to access my own (Windows 7 PC) local Public\Documents section using the same connection string, since the serverName can be changed using the program.
Still nothing.
Try this:
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\serverName\shareName\folder\myDatabase.mdb; Jet OLEDB:Database Password=g3n3r4l;Persist Security Info=False;"
You must need to test first if you can access the shared path folder on client P.C. And if it can access it there will be no problem.Make sure also that the client user is administrator so it can do CRUD using you app.
Regards
Well, I actually solved it. Wow.
It turns out, there was an extra " at the very end of the connection string from the .ini file.
//Try This One...
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
Con = new OleDbConnection(#constr);
Con.Open();
Com = new OleDbCommand();
Com.Connection = Con;

MySql's Exception : Variable 'character_set_client' can't be set to the value of 'utf16'

Previously I use sql server 2005 as my website database, and everything works well.
now I have changed to MySql server 5.5 database because it is open source.
I used Navicat Premium to transfer my data from sql server to mysql. I use mysql workbench and navicat to manage my database. Problems come when i declare the connection to mysql database. here is my code:
MySqlCommand cmdselect;
MySqlConnection conNDB;
MySqlDataReader Mydtr;
string server = "localhost";
string database = "maindb";
string uid = "root";
string password = "abc123";
string strCon = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
string strSelect = "SELECT * FROM announcement";
conNDB = new MySqlConnection(strCon);
conNDB.Open();
cmdselect = new MySqlCommand(strSelect, conNDB);
Mydtr = cmdselect.ExecuteReader();
rptAnnounce.DataSource = Mydtr;
rptAnnounce.DataBind();
Mydtr.Close();
conNDB.Close();
Reference to MySql.Data already set. Here i got this error message :
Exception Details:
MySql.Data.MySqlClient.MySqlException:
Variable 'character_set_client' can't
be set to the value of 'utf16'
Error message stated this error occurs during connection.Open();
When i keep on refreshing the error page, i got another error sometime. here is it:
Exception Details: MySql.Data.MySqlClient.MySqlException: Expected end of data packet
Error message stated this error occurs during Mydtr = cmdselect.ExecuteReader();
I am new to mysql. i don know what problem is this. i guess this problem comes from database's setting or data, not my source code.
anyone knows the solution? your help is greatly appreciated. i been trying for 4 days but cannot solve.
solved!! Thanks to #Etienne Rached and #jeremi
all the problems come from the character set problem.
solution: download navicat, to change the character set for database and every single table.
there are 2 places you need to check:
1) right-click on database eg. myDb. Then select properties and set the character set
2) right-click on a table and select design table. click every single row to change character set and finally go to "Option" tab and change the character set.
For your info: this is very rare case. I google it almost cannot find the solution. i created this mistake during installation of Mysql, I chose utf16 format ><
by the way, simple connectionstring will work. like
"server=localhost;database=maindb;uid=root;pwd=abc123;CharSet=utf8; port=3306";
Hi to add up to the above points.
As of MySQL 5.5 version, it doesn't support utf16 or utf32 character set encoding.
There are couple of things that need to be looked from both
Client making the connection to DB
DB itself
At client side, it invokes the query to DB with a query encoded in particular format and the server intact have to understand these queries and respond in particular format, that the client can understand in turn.
Point 1: So we need to set the charset at client level, in connection string as
Charset=utf8;
And in turn you have to check with DB and table (to which you are seeking a query transaction) charset and collation
There are four level of encoding charset and collation at MySQL server for flexibility
Charset for whole server server_character_set
Charset for Database
Charset for Table
Charset for Table columns as well
you can check these values using following query
show variables like 'character%';
show variables like '%collation%';
So, the point is DB server read these queries in the encoding specified in connection string.
Point 2 Instead of specifying the character set at connection string, you can also set the charset for client (in which the server interrupts ) at query after opening up connection
set names 'charset';
Ex: set names 'utf8';
There are the 3 server parameters significant in charset specific issues from client to server
character_set_client - Server sets the specified charset for client - queries passed to
character_set_connection - Server sets the specified charset for connection transaction
character_set_results - Server sets the specified charset for returned results, error messages from DB to client
Point 3 Instead of Point 1 and 2, you can set these variables at DB to ensure proper client server transaction
Basically, the client and DB(server, db table, column) encoding and collation type must be similar to avoid data losses during DB transactions.
Hope this helps.....
Could be that you are trying to talk with utf16 but the database only sopports utf8 or some other.
Try adding this to your connection string:
Character Set=utf8
My connection string looks like this:
"server=" + settings.DatabaseHost +
";User Id=" + settings.DatabaseUsername +
";password="+ settings.DatabasePassword +
";database="+ settings.DatabaseName+
";Persist Security Info=True" +
";Connect Timeout=5;Default Command Timeout=10" +
";Character Set=utf8";
If that does't work, try ASCII or latin1
This error "Exception Details: System.Collections.Generic.KeyNotFoundException:" may occur if you have not upgraded your MySql client library after upgrading your connection string character set to utf8mb4
Please update the MySql.data.dll library version to latest 6.6.5.0
Hope this should solve key not found exception.

Categories

Resources