Connecting to SQL Server 2008 R2 database from Visual Studio 2013 - c#

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.

Related

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;"

How to access the localhost connection to MySQL database through c#?

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();
}

Getting my sql database to work with my hit counter code in asp.net

I been trying to follow this tutorial to create a hit counter for my website using asp.net/c# and html/css. I'm running this off localhost. I'm having trouble configuring or getting the sql database connectionstring to work. Here is a link to the tutorial I'm using Hit counter in asp.net. So I follow the tutorial and run the code, and i get this error
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I'm pretty sure it has to do with how i wrote the ConnectionString in the web Config file. Maybe I'm pointing the data source to the wrong place? Maybe it's because i'm not using Initial Catalog in the connection string?
connectionstring in my web config file:
<connectionStrings>
<add name="ConnectionString" connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;
Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
calling my connectionstring from .cs file
/objects we will need to work with the db
SqlConnection conn;
SqlCommand cmd;
//IF PAGE IS NOT A POSTBACK, ADD A HIT
if (!Page.IsPostBack)
{
//connect to the db
conn = new
SqlConnection(WebConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString);
//the sql command to increment hits by 1
cmd = new SqlCommand("UPDATE Hits SET Hits = Hits+1 WHERE
Name=#Name", conn);
cmd.CommandType = CommandType.Text;
//update where Name is 'About' which corresponds to this page
cmd.Parameters.AddWithValue("#Name", "About");
using (conn)
{
//open the connection
conn.Open();
//send the query
cmd.ExecuteNonQuery();
}
I'm still a newbie when it comes to all this database stuff, any help be appreciated.
update fixed: I followed the instructions by user1551066 and found my data source for the database.mdf and then i plugged it in my connectionstring in web config and it WORKED.
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=
(LocalDB)\v11.0;AttachDbFilename=C:\Users\bobdole\Desktop
\VideoWebsite\VideoWebsite\VideoWebsite\App_Data\Database.mdf;
Integrated Security=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>
Try to connect to your .mdf database in visual studio. 1)Go to server explorer tab. 2)You should see your database .mdf file (possibly as DefaultConnection) 3) Click on it. In the Properties window you wil see the section Connection. Unfold it and you will see the ConnectionString property. Copy and paste it in your web.config ConnectionString setting.
Your error is due to SQL connection failure.Please check the connection string which you have passed was correct.For connection string reference please refer here.
Sql Server connection string
connetionString="Data Source=ServerName;
Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
If you have a named instance of SQL Server, you'll need to add that as well.
"Server=localhost\sqlexpress"
and for connecting SQL Server
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Please refer [here][2]

Can't connect to database server

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.

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