Can't connect to database server - c#

I'm encountering a problem with my database connection.
I started with a new blank solution, then I added a WCF library project, and last but not least a WCF website (service).
In the website i added a reference to the library where I have the interface (data contract), the class that implements the interface and the dataclasses.
what I'm trying to do is to connect to a database on a server and try to retrieve some data from there.
So the connection string looks like:
<add name="myConnectionString" connectionString="Data Source=MyServer; Initial Catalog=MyDatabase; User Id=me; Password=me123;" providerName="System.Data.SqlClient" />
and this is how I'm trying to connect with the database:
public List<string> GetEngagements(string id)
{
string sql = "SELECT myColumn FROM myTable WHERE Id = '" + id + "'";
string connString = string.Empty;
SqlConnection connDB;
connString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
connDB = new SqlConnection(connString);
SqlCommand command = new SqlCommand(sql, connDB);
connDB.Open();
SqlDataReader rdr = command.ExecuteReader();
List<string> numbers = new List<string>();
while (rdr.Read())
{
numbers.Add(rdr[0].ToString());
}
rdr.Close();
return numbers;
}
I'm getting an exception on connDB.Open().
Then exception message says:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
I've been getting this message for 2 days now, I've googled a lot and deleted the C:\Documents and Settings\username\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS directory but it didn't work for me..
Any solution???? help please

The error message:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance.
Suggests that you're using user instancing, and therefore your connection string will point to an .mdf file on disk rather than the name of a database.
So I'll assume that you want to connect to a file instance rather than a server instance.
I'll also assume that you're using SqlExpress rather than the full fat version.
In which case your connection string is wrong. It should look more like this:
"Data Source=.\SQLEXPRESS;
AttachDbFilename=fileOnDisk.mdf;
Integrated Security=True;
User Instance=True;"
User instancing means that this server instance and the DB inside will only be visible to the application opening the connection string.
You don't have to use user instancing - you can set User Instance=False or just leave it out. Then once the application has made the connection you can connect other tools to the server instance and connect to the DB yourself.

Related

C# Winforms connection to MySQL AWS Database

I'm trying to connect a winforms .net application with an AWS RDS MySQL database but I am having difficulty making the connection. I have read a lot of material about connecting through Microsoft SQL database and through Elastic Beanstalk but I haven't come across the answer I'm looking for... possibly because I'm a noob.
I've looked through a few of these questions:
How to connect to MySQL Database?
https://dev.mysql.com/doc/dev/connector-net/8.0/html/T_MySql_Data_MySqlClient_MySqlConnection.htm
using MySql.Data.MySqlClient;
string connection = "server=localhost; Database=database_URL; User Id=admin;
Password=myPassword";
myConn.Open();
MessageBox.Show("Success");
I'm getting the following error message:
MySql.Data.MySqlClient.MySqlException: 'Unable to connect to any of the specified MySQL hosts.'
Is there something simple that I'm missing? I have copied the database endpoint into the database_URL location. My user id and password are correct. My database is setup on AWS as a MySQL database.
Checking back with ConnectionStrings makes it appear as if your parameter-names are wrong. 'username' should be 'uid' and 'password' should be 'pw'.
In any case I'd suggest using the MySqlConnectionStringBuilder-class to construct your connection string.
var connectionStringBuilder = new MySqlConnectionStringBuilder
{
Server = "<Instance_Ip>",
UserID = "root",
Password = "<Password>",
Database = "<Database_Name>"
};
using (var conn = new MySqlConnection(connectionStringBuilder.ToString()))
The error message is given because can't connect to the host.
In your connection string is given the localhost as the server but your database is on cloud (AWS), so it means that you must specify the database's IP or the domain name pointing to that database, not the local (local means that is in your computer). e.g.
string conn = "server=192.168.0.7; Database=database_name; User Id=admin;
Password=myPassword";
Note that the server IP is provided by AWS, and you'd make sure that ports are enable. The most common port for MySQL is 3306.
Best regards.
Try this,
//This is my connection string i have assigned the database file address path
string MyConnection2 =
"host='localhost';database='databasename';username='myusername';password='mypassword'";
//This is my insert query in which i am taking input from the user through windows forms
string Query = "Your query";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
// Here our query will be executed and data saved into the database.
MessageBox.Show("Save Data");
while (MyReader2.Read())
{
}
MyConn2.Close();

Connect with my local .mdf database (correct code)

I have to finalize a software with local database automatically installed when any one setup the final.exe program, but I cannot connect and design code with my local database.
class Class1
{
internal static string x = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Prog\Try\StrorPro_v1.3\StrorPro_v1.3\StoreProData_v1.2.mdf;Integrated Security=True;Connect Timeout=30";
}
using (SqlConnection cn = new SqlConnection(Class1.x)) {
cn.Open();
string cm = "select id from item_new_customer where cust='" + textBox2.Text +
"' order by id";
using (SqlCommand cmd = new SqlCommand(cm, cn)) {
...
Your connection string should look similar to the example below. It isn’t necessary to reference an MDF or other file. Data Source refers to the SQL Server instance where the database is hosted. Initial Catalog will be the database that all SQL statements without the USE keyword or a three part identifier, i.e. Database.Schema.Table, are sent to. When SSPI is used for Integrated Security the Windows credentials that are used to run the application will be used in the authentication process. True is equivalent to SSPI, however it’s recommended to use SSPI. To use SQL Server authentication specify a user ID and password for the User ID and Password properties, and set Integrated Security to false. For more details on additional connection string properties you can refer to the documentation here.
“Data Source=YourSQLServerInstance;Initial Catalog=YourDatabase;Integrated Security=SSPI;"

Remote server claims table doesn't exist

I have a connection string in my config files like so
add name="entities" connectionString="Data Source=localhost;user id=username;password=somepassword;persist security info=True;database=dbname" providerName="MySql.Data.MySqlClient"
This works with localhost.
As soon as I change the Data Source to Data Source=123.34.45.56 <-- some remote server
I get MySql.Data.MySqlClient.MySqlException: Table 'mydb.Emails' doesn't exist
If I use connection code in c# it will work against the remote server : Example below
MySql.Data.MySqlClient.MySqlConnection mySqlConnection = new
MySql.Data.MySqlClient.MySqlConnection();
mySqlConnection.ConnectionString = "Data Source=123.34.45.56;user id=username;password=somepassword;persist security info=True;database=dbname";
string conString = mySqlConnection.ConnectionString;
using (MySqlConnection connection = new MySqlConnection(conString)) {
connection.Open();
using (MySqlCommand command = new MySqlCommand(
"SELECT * FROM emails",
connection)) {
using (MySqlDataReader reader = command.ExecuteReader()) {
while (reader.Read()) {
for (int i = 0; i < reader.FieldCount; i++) {
var tr = reader.GetValue(i);
}
}
}
}
}
How come the connection string in the web.config is throwing this error for every table MySql.Data.MySqlClient.MySqlException: Table 'mydb.Emails'doesn't exist.
The tables are there as the c# connection code can open a connection and query the data just fine.
How do I get the connection string to work?
John Garrard was correct. It was a case sensitivity issue with the database located on two different operating systems. I needed to make my entities case sensitive and the switching the connection string will work between the Windows development machine and the Linux production machine. Thanks.
I came across this issue when moving from a Windows dev to AWS test system. There is a parameter called "lower_case_table_names" that controls how MySql matches table names which defaults to 0 on linux and 1 in Windows (meaning case sensitive and insensitive):
On your AWS Console go to the RDS page.
Click on Parameter Groups.
Either create your own or click into the default parameter group.
Search for the parameter lower_case_table_names.
Edit the value and set it to 1
Save the parameters and restart the db instance.

Connecting to SQL Server 2008 R2 database from Visual Studio 2013

I know it is a classic problem. But I am fed up. I am trying to generate a Windows Forms application in VS 2013. For database I use SQL Server 2008 R2. The database and application are on the same system. And I use the following connection string in my app.config file
<connectionStrings>
<add name="Connectionstring1"
connectionString="Data Source=PC02;Initial Catalog=KCPIMSTest;
User ID=sa;Password=***********;Integrated Security=true"
providerName="System.Data.SqlClient"/>
</connectionStrings>
I got this connection string by adding the database to server explorer of VS 2013 and take it from properties. But while running the application I get an exception on con.open();:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Cannot open database "KCPIMSTest" requested by the login. The login failed.
Instead of Data Source=PC02, I already tried localhost, sqlexpress and all.
These are the additional codes
public void Save(string uname, string pwd)
{
string constring = getConnection();
SqlConnection con = new SqlConnection(constring);
if (con.State != ConnectionState.Open)
con.Open();
SqlCommand cmd = new SqlCommand("tblTest", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#UserName", uname);
cmd.Parameters["#UserName"].Direction = ParameterDirection.Input;
.....
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted Succesfully");
}
public static string getConnection()
{
/*Reading Connection string from App.config File */
string constr = ConfigurationManager.ConnectionStrings["Connectionstring1"].ConnectionString;
return constr;
}
If you're using a SQL server login, and assuming you have the correct password, remove Integrated Security=true from your connection string.
Reference: http://msdn.microsoft.com/en-US/library/ms254500(v=vs.80).aspx
P.S. Practice using using where possible (i.e. classes that implement IDisposable such as SqlConnection).
You should provide:
either User ID and Password (when you use SQL Server login)
or set Integrated Security=true (when you use Windows login).
Don't use both at the same time.
Data Source=PC02;Initial Catalog=KCPIMSTest;
User ID=sa;Password=***********
Remove Integrated Security. Then change your password=***** to password=youroriginalpasswordtext Then your login will work and
I think you copied this connection string from the ServerExplorer. The passwords will be Masked by default. So you should change the Mask to original Password itself.

How to connect to the Remote Database using Connection String in C#.net

every one. I want to connect a remote database using Sql Connection String in C#.net, I am trying it to do, but failed to connect. I am new to C#.net connections to the Database. Can any one pls tell me how to write the Connection String.
Check this website for the specific format: http://www.connectionstrings.com/
Here is a little bit of code that will connect to a dabase called myDatabase on a server called myServer, query the myTable table for the column myColumn, and insert the returned data into a list of strings.
While by no means exaustive or perfect, this snippet does show some of the core aspects of working with data in C#.
List<string> results = new List<string>();
SqlConnection conn = new SqlConnection("Data Source = myServerAddress; Initial Catalog = myDataBase; User Id = myUsername; Password = myPassword;");
using (SqlCommand command = new SqlCommand())
{
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = "Select myColumn from myTable";
using (SqlDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
results.Add(dr["myColumn"].ToString());
}
}
}
There is no difference in this regard. The connection string to connect to remote server database is written same as you write to connect to local database server.
However, only Data Source changes.
Below is a sample connection string
User ID=dbUserName;Password=dbUserPwd;Initial Catalog=dbName;Data Source=remoteMachine\serverInstanceNameIfAny;
But by default sql server is not configured to Sql Server Authentication, so you need to enable
Sql server authentication
Also Create a Log in user in the database
Here are a couple of examples:
With Integrated Security
Server=RemoteMachineName\Intance; Initial Catalog=DatabaseName; Integrated Security=true;
With username and password
Server=RemoteMachineName\Intance; Initial Catalog=DatabaseName; UID=Username; PWD=Password;
You can also do that in web.config file
<configuration>
<ConnectionStrings>
<add name="YourConnectionString" connectionString="Data Source=Nameofserver;
InitialCatalog=NameofDatabase;Persist Security Info=True;
UserID=DatabaseUserID;Password=DatabasePassword" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>

Categories

Resources