change connection string for dataset - c#

How to create authentication window for database when I use dataset - MyDatabaseDataSet?
When I didn't use dataset I simply open new SqlConnection for every operation and use some connection string which was created after I writed Login and Password. But Dataset use some default connection string. How to change it?
I want to connect to database and tables with connection string Data Source=XXXX-PC\MSSQLSERVER2;Initial Catalog=MyDatabase;User ID={0};Password={1} where {0} and {1} - parameters from authentication window.
I don't understand where to put my connection string and then use it as default connection string.

I've had problems in the past with DataSet objects using a default connection string.
To get around this, I pass the connection string into my SqlConnection constructor.
In my case I'm using a web.config to hold the connection string.
var dt1 = new CustomDataSet.CustomDataTable();
var connectionString = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString
using (var connection = new SqlConnection(connectionString))
{
using (var da1 = new GetCustomDataTableAdapter() { Connection = connection })
{
da1.Fill(dt1, id);
}
}

Related

Removed database out of connection string

I was given a method to get our database connection string to Sql Server:
SqlConnection GetConnectionString()
I call that and get what the connection string should be. If the database does not exist, I need the connection string without the database name in it. If I try to use the connection string with the database name in it, I get an error that it cannot connect to the database, which is it since it does not exist.
I am calling like this:
using (var connection = new SqlConnection(GetConnectionString().ConnectionString))
Is there a way to recreate the connection string easily without the database name?
SqlConnectionStringBuilder aBuilder =
new SqlConnectionStringBuilder(yourConnectionStringWithDatabase);
aBuilder.InitialCatalog = "";
string yourConnectionStringWithoutDatabase = aBuilder.ConnectionString;
It's easy
var connectionString = "data source=someInstance;initial catalog =someDatabase;etc.";
var pattern = "initial catalog[=\\s\\w]+;";
var dbRemoved = Regex.Replace(connectionString, pattern, "");
Note that I haven't handled case sensitivity, but this should be a good start for your requirements.

Connecting to mysql on 000webhost using C#

Im simply just trying to read what there is in the batabase on to a console but i always get an exception on the conn.Open() line. Here is all the code:
SqlConnectionStringBuilder conn_string = new SqlConnectionStringBuilder();
conn_string.DataSource = "mysql14.000webhost.com"; // Server
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxx";
conn_string.InitialCatalog = "a7709578_codecal"; // Database name
SqlConnection conn = new SqlConnection(conn_string.ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("Select name FROM Users");
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1));
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
You need to build the connection string manually or use MySqlConnectionStringBuilder. MySql uses a different format than SQL Server and the SqlConnectionStringBuilder that you're using. You also need to use a MySQL library, SqlConnection, SqlCommand, etc are all build specifically for SQL Server.
MySQL connectors
For MySQL database you are using wrong provider. Those classes you have used in posted code are for SQL Server. Your code should look like below with MySQL provider related classes
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql14.000webhost.com";
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxxxx";
conn_string.Database = "a7709578_codecal";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
Check Related post in SO
Also to point out, you are selecting only one column from your table as can be seen
new SqlCommand("Select name FROM Users");
Whereas trying to retrieve two column value, which is not correct
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1))
000webhost free servers does not allow external connections to the server database.
You can only use your database from your PHP scripts stored on the server.
You can get data from database using PHP and it will return.So i advice to you using php from C# like api.

Connect to database using sql server authentication programatically

How can I connect to database using sql server authentication programmatically in c# winforms? I mean i created a login named loginTesting with a loginTesting as user in sql server 2012. I want to access that login in c# by accepting user inputs from textbox. Thanks.
You can use the class SqlConnectionStringBuilder to construct the connection string that you will need for a SqlConnection object:
SqlConnectionStringBuilder scsBuilder = new SqlConnectionStringBuilder();
scsBuilder.UserID = "username";
scsBuilder.Password = "password";
scsBuilder.DataSource = "servername or ip address";
scsBuilder.InitialCatalog = "databasename";
scsBuilder.IntegratedSecurity = false;
using (SqlConnection sqlCon = new SqlConnection(scsBuilder.ConnectionString))
{
// perform your SQL tasks
}
Further reading here:
SqlConnectionStringBuilder Class
SqlConnection Class
Expanding on Answer 1, if you'd like to test your usernames/passwords based on user input you could use the SqlConnectionStringBuilder object as shown in this example:
SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();
connectionString.ConnectionString = #"data source=.;initial catalog=master;";
connectionString.UserID = "username";
connectionString.Password = "password";
using (var sqlConnection = new SqlConnection(connectionString.ConnectionString))
{
}
You need to create a new SQLConnection (and clear it up once you've used it).
using(var connection = new SqlConnection(connectionString))
{
// Do something
}
The tricky bit is getting the correct connection string, but fortunately there are resources to help. Checkout ConnectionStrings.com to find a connection string that looks like it should work, plug in your credentials/server etc and you're good to go.

Is there a way to get the connection string from a SQL DB then use that through the application?

I am just doing some research at the moment into this and would like to know if it's possible.
I have an application where someone logs in with a username/ I would like to have a table with all the company id's stored and depending on which one they log in using it will use a connection string from the DB for that company.
I am fully aware of how to do it with the web.config but want to minimise the information kept here because potentially we are talking of around 1,000 connection strings.
Sure create a table or modify an existing table.
CREATE TABLE Connection
(
Id INT IDENTITY NOT NULL PRIMARY KEY
,ConnectionString VARCHAR(100) NOT NULL
);
INSERT INTO Connection (ConnectionString)
VALUES ('Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;');
I would advise against storing passwords in the connection string when the contents of the table are unencrypted. Setup a domain account with Sql Server privileges to run your IIS app pool or Windows Service under.
const string Query = "SELECT ConnectionString FROM Connection WHERE Id = #Id";
public string GetConnectionString(int id)
{
using(var connection = GetConnection())
using(var command = new SqlCommand(Query, connection))
{
command.Parameters.AddWithValue("#Id", id);
connection.Open();
using(var reader = command.ExecuteReader())
{
if(reader.Read())
{
return Convert.ToString(reader["ConnectionString"]);
}
}
}
}
var connectionString = GetConnectionString(1);
using(var connection = new SqlConnection(connectionString))
{
//logic
}
Yes, this is possible.
Store the connection strings in your (main?) DB, retrieve them and use them when instantiating new DdConnections.
Most of the classes that inherit from DbConnection (SqlConnection, for example) have a constructor overload that takes a connection string.

How To Work With SQL Database Added As Item In Visual Studio 2008?

If I'm letting Visual Studio take care of adding an SQL Server database to an existing project, it adds the connection string to app.config. How can I use use THAT connection string to make my own connections and datasets?
Use the ConfigurationManager.AppSettings to read the connection string when required.
For example, if you opening a SQL Connection, use the assign the "Connection String" property to the value retrieved from ConfigurationManager.AppSettings ("MyConnectionString")
If it is placed in the appropriate section in the app config file, then you can use ConfigurationManager.ConnectionStrings to retrieve it as well.
Read more here http://msdn.microsoft.com/en-us/library/ms254494.aspx
Place the connection string in your app.config then use
ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
to get the connection string.
For example:
private string GetConnectionString(string str)
{
//variable to hold our return value
string conn = string.Empty;
//check if a value was provided
if (!string.IsNullOrEmpty(str))
{
//name provided so search for that connection
conn = ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
}
else
//name not provided, get the 'default' connection
{
conn = ConfigurationManager.ConnectionStrings[ConnStr].ConnectionString;
}
//return the value
return conn;
}
Then you can reference the connection using ado.net or Linq
For Example:
your app.config would contain an entry like:
<connectionStrings>
<add name="nameofConnString" connectionString="Data Source=SQLDATA;Initial Catalog="nameofdatabase";Persist Security Info=True;User ID=username;Password=password;Connection Timeout=30;Pooling=True; Max Pool Size=200" providerName="System.Data.SqlClient"/>
'
Then you could call
conStr = GetConnectionString("nameofConnString")
With Ado.net
You could then establish the connection with:
sqlConn = new SqlConnection(conStr);
sqlConn.Open();
Or with Linq
LinqData ld = new LinqData();
DataContext dataContext = new DataContext(ld.GetConnectionString(sqlConn));
where LinqData is a class that contains the GetConnectionString() method.
Well, both of those helped get me on the right track. I found this quite simple, yet highly annoying. The solution I used was:
using System.Configuration;
add a reference System.configuration
create a new connection with SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabaseConnectionFromApp.Config"].ConnectionString)

Categories