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.
Related
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.
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.
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);
}
}
I can successfully log on to the database with this:
MySqlConnection conn = new MySqlConnection();
MySqlConnectionStringBuilder connString = new MySqlConnectionStringBuilder();
connString.Server = textEditServer.Text;
connString.UserID = "root";
connString.Password = textEditServerPassword.Text;
connString.Database = "geysercontrol";
conn.ConnectionString = connString.ConnectionString;
try
{
conn.Open();
Properties.Settings.Default.Properties["ConnectionString"].DefaultValue = conn.ConnectionString;
conn.Close();
}
catch (MySqlException)
{
XtraMessageBox.Show("No connection could be established");
}
But when I try to use the ConnectionString property to reconnect with different class, I get an MySQLException saying
Access denied for user 'root'#'localhost' (using password: NO)
What can be the possible causes to this? The page on possible causes on the MySQL website doesn't include my situation.
The code I use to reconnect is:
connection = new MySqlConnection();
connection.ConnectionString = (String)Properties.Settings.Default.Properties["ConnectionString"].DefaultValue;
connection.Open();
And the connectionString definitely is the same in both cases. It is:
server=localhost;User Id=root;database=geysercontrol;password=password
Add persist security info = true to the connection string I think.
If it were me though I wouldn't put connection string with a password in it in there. If you ever call Save, it will be exposed in the config file.
I am looking for a way to connect to sybase from C# without having to setup an ODBC DSN connection locally on the machine.
Is this possible? I tried all of these different connection strings:
static private DataTable Run(string sql)
{
var conn = new OdbcConnection();
const string CONN_STRING2 =
"Data Source='[myServer]';Port=5020;Database=[dbName];Uid=[user];Pwd=[pwd];";
const string CONN_STRING1 =
"Provider=Sybase.ASEOLEDBProvider.2;Server Name=[myServer];Server Port Address=5020;Initial Catalog=[dbName];User ID=[user];Password=[pwd];";
conn.Open();
var da = new OdbcDataAdapter { SelectCommand = conn.CreateCommand() };
da.SelectCommand.CommandText = sql;
var dt = new DataTable();
da.Fill(dt);
da.Dispose();
conn.Close();
return dt;
}
But I got an error stating:
{"ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"}
You are using var conn = new OdbcConnection(). That is why you are getting the error.
You will need to use a sybase oledb client library. I don't know sybase at all but last I heard one needed to purchase a third-party provider. This was almost three years ago so they may have one by now.
You would then need to do something like var connection = new ASEConnection().
Download the DLL from the following link:
Sybase library
Use this library for connection:
ASEconnection connection = new AseConnection();
Use specific ADO.Net data provider stright from manufacturer (SAP now own sybase). I think you can manage to create a connection string yourself using this reference. For example:
var connStr = #"Data Source=\\myserver\myvolume\mypat\mydd.add;User ID=myUsername;
Password=myPassword;ServerType=REMOTE;"
using (ASEConnection conn = new AseConnection(connStr)) {
// use conn
}
Same informaton can be obtained from documentation mentioned earlier.