SQL connection c# - c#

I have a standart local Oracle DB to which i can connect with my sqldeveloper
using connection with :
username = system
password = orcl
hostname = localhost
port = 1521
SID = ORCL
but when i'm trying to do this in the code
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.InitialCatalog = "HR_ORCL";
builder.UserID = "system";
builder.Password = "orcl";
string connectionString = "Server=(local);Database=HR_ORCL;User ID=system;Password=orcl";
using (SqlConnection connection = new SqlConnection())
{
connection.ConnectionString = builder.ConnectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
}
}
catch(Exception error)
{
System.Console.WriteLine(error.Message);
}
I'm getting an error
"provider: Named Pipes Provider, error: 40 - Could not open a
connection to SQL server"
What am i doing wrong ?

As correctly said by Stefan you need to download and install ODP from this site
Once the installation is done you need to add a reference of the assembly Oracle.DataAccess.dll.
And then you can use it like this:
using System;
using Oracle.DataAccess.Client;
class MyClass
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "yourconnectionstring";
con.Open();
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
//some code
}
}

Related

Unable to connect to any of the specified MySQL hosts only on visual studio/C#

private void createAccount(object sender, EventArgs e)
{
Console.WriteLine("Still here");
string usernameString = username.Text;
string passwordString = password.Text;
string repeatpasswordString = repeatpassword.Text;
string emailString = email.Text;
MySqlConnection connection;
connectionString = "server=;uid=root;pwd=root;database=mydb;";
connection = new MySqlConnection(connectionString); //create connection
connection.Open(); //connects
// if (passwordString.Equals(repeatpasswordString)) {
Console.WriteLine("Clicked");
Console.WriteLine(usernameString);
commandString = "INSERT INTO account (username,password,email) VALUES (${username}, ${password}, ${email})";
MySqlCommand command = new MySqlCommand(commandString, connection);
MySqlDataReader myReader;
myReader = command.ExecuteReader();
//}
}
}
Thats my code, I can connect to my database fine with the same credentials on python. Thanks a lot!
EDIT: The error I am getting is MySql.Data.MySqlClient.MySqlException: 'Unable to connect to any of the specified MySQL hosts.'
It's necessary to specify the server parameter. If you run the database locally, then you can change your line to:
connectionString = "server=localhost;uid=root;pwd=root;database=mydb;";
or
connectionString = "server=127.0.0.1;uid=root;pwd=root;database=mydb;";
If you run the database not locally, you should add your server host address.
If your connection string is
connectionString = "server=;uid=root;pwd=root;database=mydb;";
Then is wrong connection string. You must fill server address, for example:
connectionString = "server=localhost;uid=root;pwd=root;database=mydb;";
More examples you can find here

Generating SQL Database on Client PC

I have an application that uses SQL Server and I am working on a setup that should generate the Database on the Client machine from a script.
As a prerequisite for installation I have selected SQL Server Express 2012 and the .Net Framework.
My question is, will SQL Server Express 2012 be enough to make accessing the database possible on the Client machine?
Also, will my Code for generating the Database from the script run on another PC, specifically the "Data Source=.\BeneSQL" worries me, since that is "unique" to my PC, or will the script generate that part aswell?
private void Form1_Load(object sender, EventArgs e)
{
if (!CheckDatabaseExist())
{
GenerateDatabase();
}
}
private bool CheckDatabaseExist()
{
SqlConnection sqlConnection = new SqlConnection(#"Data Source=.\BeneSQL;Initial Catalog=TryingDB;Integrated Security=True");
try
{
sqlConnection.Open();
return true;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return false;
}
}
private void GenerateDatabase()
{
List<string> cmds = new List<string>();
if (File.Exists(Application.StartupPath + "\\Skript.sql"))
{
TextReader tr = new StreamReader(Application.StartupPath + "\\Skript.sql");
string line = "";
string cmd = "";
while ((line = tr.ReadLine()) != null)
{
if (line.Trim().ToUpper() == "GO")
{
cmds.Add(cmd);
cmd = "";
}
else
{
cmd += line + "\r\n";
}
}
if (cmd.Length > 0)
{
cmds.Add(cmd);
cmd = "";
}
tr.Close();
}
if (cmds.Count > 0)
{
SqlCommand command = new SqlCommand();
command.Connection = new SqlConnection(#"Data Source=.\BeneSQL;Initial Catalog=MASTER;Integrated Security=True");
command.CommandType = System.Data.CommandType.Text;
command.Connection.Open();
for(int i=0; i<cmds.Count; i++)
{
command.CommandText = cmds[i];
command.ExecuteNonQuery();
}
}
}
It depends on what instance name will be used for the SQL Server 2012 installation.
If SQL Server is installed on a default instance (.) without name, your code will not work, because it will not be able to connect to the instance .\BeneSQL , because it will not exist.
Otherwise, if SQL Server is installed on an instance named BeneSQL , then your code should work, because it will find the instance.
I can't see that working for the reasons you suspect.
Try
command.Connection = new SqlConnection(#"Data Source=localhost;Initial Catalog=MASTER;Integrated Security=True");

How to connect to Oracle database

I am using below code to connect to an oracle server. I need to particularly use OdbcConnection class because I am doing enhancement of an existing application which currently connects to SQL Server using this method. So I have to use the same method for other DBMS also.
I have tried with the code below:
const string ConnectionString = #"SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MachineName.Domain.com)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=orcl.Domain.com)));uid=system;pwd=user";
using (OdbcConnection connection = new OdbcConnection(ConnectionString))
{
connection.Open();
}
But I get an exception when calling the Open() method as follows:
"ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
Any idea of what I am doing wrong here?
Have a look at Oracle connection strings
You connectionString should be like this:
var DB = #"SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MachineName.Domain.com)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=orcl.Domain.com)))";
string ConnectionString = "Driver={Oracle in OraClient11g_home1};Dbq=" + DB + ";uid=system;pwd=user;"
The driver name might be different on your machine. You could also use the ODBC driver from Microsoft (Driver={Microsoft ODBC for Oracle};Server=...), however this is deprecated for ages.
Actually I prefer the DbConnectionStringBuilder (or even OdbcConnectionStringBuilder)
var str = new DbConnectionStringBuilder(true);
str.Add("Driver", "Oracle in OraClient11g_home1");
str.Add("Dbq", #"(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MachineName.Domain.com)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=orcl.Domain.com)))");
str.Add("Uid", "system");
str.Add("Pwd", "user");
string ConnectionString = str.ConnectionString;
///Your connection string should be like
string str = Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = abc )(PORT = 123))(CONNECT_DATA =(SID = xyz)));User Id=abc_xyz;Password=111;Min Pool Size=10;Connection Lifetime=120;Connection Timeout=600;Incr Pool Size=5; Decr Pool Size=2;validate connection=true;
using (OracleConnection con = new OracleConnection(str))
{
using (OracleCommand cmd = con.CreateCommand())
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = RoutineConstant.Text;
cmd.BindByName = true;
cmd.ExecuteNonQuery();
if (cmd.Parameters["Value"].Value != null && cmd.Parameters["Value"].Value != DBNull.Value)
{
return Convert.ToDecimal(cmd.Parameters["Value"].Value.ToString());
}
}
}

Unable to read from Azure database

I'm trying to read/write to an Azure database but I receive the following error message when using the SqlDataReader in my code below:
Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.
I can connect to the database in SQL Server Management Studio. Any suggestions as to why this might be and how to resolve this?
My C# code:
string connectionString = "Server=tcp:[xxxxx].database.windows.net,1433;Database=[xxxxx];User ID=[xxxxx]#[xxxxx];Password=[xxxxx];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = "SELECT [xxxxx], [xxxxx] FROM [xxxxx]";
using (SqlCommand cmd = new SqlCommand(sql))
{
using (SqlDataReader reader = Database.ExecuteReader(cmd))
{
if (!reader.Read())
{
throw new Exception("[xxxxx] not found.");
}
else
{
name = Database.GetStringValue(reader, "[xxxxx]", "");
}
}
}
}
Make sure the IP you are connecting to the database form is white listed on your database configuration in Azure. Sounds like a firewall problem to me.
I don't know how but rearranging my code to the following below resolved my issue and I could read the data that I wanted.
string connectionString = "Server=tcp: [xxxxx].database.windows.net,1433;Database=[xxxxx];User ID=[xxxxx]#[xxxxx];Password=[xxxxx];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
SqlConnection myConnection = new SqlConnection(connectionString);
try
{
myConnection.Open();
SqlDataReader reader = null;
SqlCommand myCommand = new SqlCommand("SELECT [xxxxx] FROM [xxxxx]", myConnection);
reader = myCommand.ExecuteReader();
if (!(reader.Read()))
throw new Exception("[xxxxx] not found.");
else
cert = reader["[xxxxx]"].ToString();
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

Set database backup file on local machine

POSSIBLE DUPLICATE OF :
How to create SQL Server 2008 database full backup programmatically in desired folder
I have a database on my computer (SQL Server 2008 Express).
I need any sample code in C# that I can use to backup the database to a file using Visual Studio 2010.
Thanks..
i'll using this code to connect Database
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
Just execute SQL Server command
BACKUP DATABASE database_name TO DISK='d:\path\to\backup\file\on\the\server.bak'
from your program
EDIT
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;
Integrated Security=True; User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
SqlCommand command;
command = new SqlCommand(#"backup database SMS_DB.mdf to disk ='" + path + "\\" + name, con);
command.ExecuteNonQuery();
MessageBox.Show("Backup Created.");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
Try this peice of code.
Im using flowing code to connect database
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
can i use your SQL Command to set backup using upon type connection
This what I did and it Worked!
private void BackupButtonClick(object sender, RoutedEventArgs e)
{
// FILE NAME WITH DATE DISTICNTION
string fileName = string.Format("SchoolBackup_{0}.bak", DateTime.Now.ToString("yyyy_MM_dd_h_mm_tt"));
try
{
// YOUR SEREVER OR MACHINE NAME
Server dbServer = new Server (new ServerConnection("DESKTOP"));
Microsoft.SqlServer.Management.Smo.Backup dbBackup = new Microsoft.SqlServer.Management.Smo.Backup()
{
Action = BackupActionType.Database,
Database = "School"
};
dbBackup.Devices.AddDevice(#backupDirectory() +"\\"+ fileName, DeviceType.File);
dbBackup.Initialize = true;
dbBackup.SqlBackupAsync(dbServer);
MessageBox.Show("Backup", "Backup Completed!");
}
catch(Exception err)
{
System.Windows.MessageBox.Show(err.ToString());
}
}
// THE DIRECTOTRY YOU WANT TO SAVE IN
public string backupDirectory()
{
using (var dialog = new FolderBrowserDialog())
{
var result = dialog.ShowDialog();
return dialog.SelectedPath;
}
}

Categories