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;"
Related
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.
I am trying to create an application which will synchronize its database with another software's database..
Problems are:
How will the database will synchronize with external database after I have created the installer and installed..i.e. how will it take the connection string.
I am looking for a solution which will provide a button to select the required database and based on the selection automatically generate the connection string.
Is it possible to run SQL create queries on external database while installation after the database is selected via browse button?
You have an option to create a Connection Settings form, which will help user to construct the connection string.
Yes, it's possible. It looks something like this:
using (var sqlConnection = new SqlConnection(#"Data Source=myServerAddress;User Id=myUsername;Password=myPassword;"))
{
sqlConnection.Open();
string query = "CREATE DATABASE...";
using (var sqlCommand = new SqlCommand())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = query;
sqlCommand.ExecuteNonQuery();
}
}
If it won't work, try to set Initial Catalog to master:
#"Data Source=myServerAddress;Initial Catalog=master;User Id=myUsername;Password=myPassword;"
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.
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>