In my C# code, I have this in my App.config
<add name="SampleDB" connectionString="Server=.;Database=Sample;Trusted_Connection=True;" providerName="System.Data.SqlClient"/>
I opened MySQL Command Client, typed in the password, then created the Sample database by typing CREATE DATABASE SAMPLE;
However, I cannot connect to the database. Do I need to specify the instance of SQL after "Server=.?
Or do I need to open the connection some other way?
Bookmark the ConnectionStrings.com. This site provides all types of connectionstring information for all types of databases and versions of drivers, including MySQL.
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;
Pwd=myPassword;
Put a piece of code here starting from the declaration of the MySqlConnection object so we can better understand why it is not connecting because the connection string answer above is already correct. If you installed MySQL using default settings, it should be:
<appSettings>
<add key="MyConnectionSettings" value="Server=127.0.0.1;Port=3306;Database=myDataBase;Uid=root or user;
Pwd=yourpassword" />
string connectionFromConfig = ConfigurationManager.AppSettings["MyConnectionSettings"];
using(MySqlConnection con = new MySqlConnection(connectionFromConfig)){
con.Open();
string sql = "SELECT *from yourtable";
MySqlCommand cmd = new MySqlCommand(sql, con );
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]+" -- "+rdr[1]);
}
rdr.Close();
}
Related
I am trying to connect to SQL Server and get data. This is what I did, but it's not working:
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=(IP)\PC-NAME\SQLEXPRESS,3306;Network Library=DBMSSOCN;Initial Catalog=dbase;User ID=sa;Password=password";
cnn = new SqlConnection(connectionString);
cnn.Open();
MessageBox.Show("Connection Open !");
cnn.Close();
Your Code is Correct, except your connection string i think
So, first, connect to your database via server Explorer in VisualStudio\View menu
Then right-click on your database and select properties and check the connection string and copy that for test
I think you have a problem with your connection string.
Check your connection string using this given example:
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial
Catalog=myDataBase;User ID=myUsername;Password=myPassword;
I am new to C# and SQL Server 2014 Express and I am using Windows forms.
I am building the small application which read/write from/to SQL Server database.
I am trying to automatically attach SQL Server database, then read data from a table named Test_Table and then fill a Datagridview.
The code I used:
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand MyCommand= new SqlCommand();
DataTable DataTable = new DataTable();
SqlDataAdapter Sql_Data_Adapter= new SqlDataAdapter();
private void button1_Click(object sender, EventArgs e)
{
MyConnection.Open();
MyCommand.CommandText = "SELECT * FROM Test_Table ";
MyCommand.Connection = MyConnection;
Sql_Data_Adapter.SelectCommand = MyCommand;
Sql_Data_Adapter.Fill(DataTable);
dataGridView1.DataSource = DataTable;
MyCommand.Parameters.Clear();
Sql_Data_Adapter.Dispose();
MyConnection.Close();
}
App.config:
<connectionStrings>
<add name="MyConnectionString"
connectionString="Data Source=localhost; AttachDbFilename=D:\\DB\\MyDB.mdf;Integrated Security=True"/>
</connectionStrings>
When I click on button1 it throws an error:
An attempt to attach an auto-named database for file D:\DB\MyDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I have no other databases attached and the database path is correct.
I had a look here, here and here but non of them helped.
Any idea how can I automatically attach a SQL Server database file? Thank you
What is the version of SQL Server are you using? This will explain a lot about your error message.
Your Connection String:
"Data Source=localhost; AttachDbFilename=D:\DB\MyDB.mdf;Integrated
Security=True"
You can only use AttachDbFilename with SQL Express. In your connection string, the Data Source is set to localhost. That sounds like you have a full version SQL Server installed.
If you have a full version of SQL Server installed, you can only attach a database via Management Studio.
If you are using SQL Express, change your data source:
Data Source=.\SQLEXPRESS
When use Oledb c# connection
I noticed that a lot connection using file.
But how to connect to localhost using oledb?
I created database and tables using Microsoft SQL Server Management that connect with SQL Express and using window authentication
When using this function i don't know how should convert to connect to localhost
//Want the connString to connect localhost instead of file
public static string connString = #"Provider=Microsoft.JET.OLEDB.4.0;data source=" + Path + "\\database\\errDB.mdb";
public static OleDbConnection connection;
public myFunction()
{
string sqlString = "SELECT name,contact,accessLevel,Crudential_ID FROM errors where Crudential_ID =#ID";
connection = new OleDbConnection(connString);
OleDbCommand command = new OleDbCommand(sqlString, connection);
//Open connection
connection.Open();
command.Parameters.Add("#ID", OleDbType.VarChar);
command.Parameters["#ID"].Value = "test";
//Read from database
OleDbDataReader reader = command.ExecuteReader();
if(reader.HasRows)
{
.....
}
connection.Close();
}
connectionstrings.com - true to its name - is indispensable when you frequently need to construct connection strings. For your specific case, this would be the relevant section.
Based on that, your connection string should look something like this:
Provider=SQLNCLI11;Server=.\SQLEXPRESS;Database=SOMEDATABASE;Trusted_Connection=yes;
To break it down:
SQLNCLI11 is the SQL Native Client OLEDB provider. You can see available providers in SQL Management Studio, under Server Objects > Linked Servers > Providers.
.\SQLEXPRESS is your servername and instance. The . is shorthand for localhost (you can also use localhost if you prefer), and SQLEXPRESS is the default instance name that SQL Express installs under.
SOMEDATABASE - whatever your database name is.
Trusted_Connection=yes - Use windows authentication. Sometime you see it as Integrated Security=SSPI. They are one and the same.
If you are using SQL Express then I would suggest using a System.Data.SqlClient.SqlConnection object to make your connection. You will only need your server name to connect.
Server=ServerName\SQLEXPRESS;Database=Blah;User ID=user;Password=pw
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.
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>