C# SQL Connection String returning error - c#

Hi I'm new when it comes to connecting to a server/database and was wondering why this returns an error.
I have a FastHost server with a database.
I've just put in an example IP but i have been using the one given on my control panel on the site.
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012" +
"Initial Catalog = DiscoverThePlanet" +
"User ID = TestUser" +
"Password = Test";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
This returns the
Can not open Connection!" message.
I get the following show in my code:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I know my server is fine because i have connected to it on SQL Server Management studio and added tables and data.

You're missing a couple of ;
conn.ConnectionString =
"Data Source = 123.456.789.012" +
";Initial Catalog = DiscoverThePlanet" +
";User ID = TestUser" +
";Password = Test";
An even better solution is to use ConnectionStringBuilder.
System.Data.SqlClient.SqlConnectionStringBuilder builder =
new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "123.456.789.012";
builder["Initial Catalog"] = "DiscoverThePlanet";
builder["User ID"] = "TestUser";
builder["Password"] = "Test";
Console.WriteLine(builder.ConnectionString);
Or (as #Fischermaen mentioned) you can use the properties, instead of indexes. It's even more readable!
builder.DataSource = "123.456.789.012";
builder.InitialCatalog = "DiscoverThePlanet";
builder.UserID = "TestUser";
builder.Password = "Test";
Also, in this scenario you aren't using any user input, but beware of connection string injection when manually creating your connection string. ConnectionStringBuilder can help you avoid those.
A connection string injection attack can occur when dynamic string
concatenation is used to build connection strings that are based on
user input. If the string is not validated and malicious text or
characters not escaped, an attacker can potentially access sensitive
data or other resources on the server. For example, an attacker could
mount an attack by supplying a semicolon and appending an additional
value. The connection string is parsed by using a "last one wins"
algorithm, and the hostile input is substituted for a legitimate
value.
The connection string builder classes are designed to eliminate
guesswork and protect against syntax errors and security
vulnerabilities. They provide methods and properties corresponding to
the known key/value pairs permitted by each data provider. Each class
maintains a fixed collection of synonyms and can translate from a
synonym to the corresponding well-known key name. Checks are performed
for valid key/value pairs and an invalid pair throws an exception. In
addition, injected values are handled in a safe manner.
A last (and, in my opinion, best) alternative is to move your connectionstring from code into a config. This will make it much easier for you to use the same code in different environments.
conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString];
And your config.
<connectionStrings>
<add name="MyConnectionString" connectionString="[ConnectionString goes here]" providerName="System.Data.SqlClient" />
</connectionStrings>

Add a semicolon after each part of your connection string code:
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
https://www.connectionstrings.com/sql-server/ should tell you more about the correct format.

Your connectionstring is not well formated, you forgot some ; :
"Data Source = 123.456.789.012;Initial Catalog = DiscoverThePlanet;User ID = TestUser;Password = Test"
An example :
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
https://www.connectionstrings.com/sql-server/

There are some ';' missing. Try this:
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test;";

Use StringBuilder if you wants to write ConnectionString like mention,
String object it will occupy memory each time.
StringBuilder will occupy memory only once, so it will give you better performance.
SqlConnection conn = new SqlConnection();
StringBuilder sb=new StringBuilder();
sb.Append("Data Source = 123.456.789.012;");
sb.Append("Initial Catalog = DiscoverThePlanet;");
sb.Append("User ID = TestUser;");
sb.Append("Password = Test;");
conn.ConnectionString =sb.ToString();
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}

Semi Column is missing in the Connection String. So correct it
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test;";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}

Related

AccessViolationException thrown by OleDbConnection.Open()

I am getting a System.AccessViolationException error when trying to use the .Open() method on my OleDbConnection variable. But, confoundingly, it doesn't seem to happen when I run my code on a different computer.
My code is for a service that I want running on a server. It appears to work correctly when I run it on my personal computer, but it throws the AccessViolationException error when I try running it on the server.
Code Versions:
I am writing in C# using Visual Studios 2019 on Windows 10
OleDbConnection is from "Assembly System.Data, Version=4.0.0.0"
ADOX is from "Assembly Interop.ADOX, Version=2.8.0.0", System.Runtime.InteropServices
ADODB is from "Assembly Interop.ADODB, Version=2.8.0.0", System.Runtime.InteropServices
My code:
internal static bool CreateMDB(MySchemaClass schema, string filePath)
{
OleDbConnection conn = null;
bool status = true;
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", filePath);
try
{
// Setup new file
catalog.Create(connectionString);
((ADODB.Connection)catalog.ActiveConnection).Close();
conn = new OleDbConnection(connectionString);
conn.Open(); // <-- Error occurs here
// Write to new file
WriteDataToFile(schema, conn);
}
catch (Exception ex)
{
status = false;
}
finally
{
if (conn != null)
conn.Close();
}
return status;
}
StackTrace:
The best lead I have found so far is this post, but I'm a bit hazy about how to proceed from that starting point.
To programmatically create an Access database do the following:
Add reference to Microsoft ADO Ext. 6.0 for DDL and Security
In VS menu, click Project
Select Add Reference
Click COM
Check Microsoft ADO Ext. 6.0 for DDL and Security
CreateAccessDatabase
public static string CreateAccessDatabase(string fullyQualifiedAccessFilename, string dbPassword = "")
{
string connectionString = String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}", fullyQualifiedAccessFilename);
if (String.IsNullOrEmpty(fullyQualifiedAccessFilename))
{
throw new Exception("Error (CreateAccessDatabase) - Database filename is null or empty.");
}
if (!String.IsNullOrEmpty(dbPassword))
{
connectionString = String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0};Jet OLEDB:Database Password='{1}'", fullyQualifiedAccessFilename, dbPassword);
}
//create new instance
ADOX.Catalog cat = new ADOX.Catalog();
//create Access database
cat.Create(connectionString);
//close connection
cat.ActiveConnection.Close();
//release COM object
System.Runtime.InteropServices.Marshal.ReleaseComObject(cat);
GC.Collect();
cat = null;
return String.Format("Database created '{0}'", fullyQualifiedAccessFilename);
}
Usage:
string result = string.Empty;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Access Database 2000-2003 (*.mdb)|*.mdb|Access Database 2007 (*.accdb)|*.accdb";
if (sfd.ShowDialog() == DialogResult.OK)
{
//create Access database
result = CreateAccessDatabase(sfd.FileName);
}
To programmatically create a table in an Access database:
Add using statement:
using System.Data.OleDb;
CreateTableProduct:
public static int CreateTableProduct(string fullyQualifiedAccessFilename, string dbPassword = "")
{
int result = 0;
string connectionString = String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}", fullyQualifiedAccessFilename);
if (!String.IsNullOrEmpty(dbPassword))
{
connectionString = String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0};Jet OLEDB:Database Password='{1}'", fullyQualifiedAccessFilename, dbPassword);
}
string sqlText = string.Empty;
sqlText = "CREATE TABLE Product ";
sqlText += "(ID AUTOINCREMENT not null primary key,";
sqlText += " Name varchar(50) not null,";
sqlText += " Price currency, Quantity integer);";
using (OleDbConnection con = new OleDbConnection(connectionString))
{
//open connection
con.Open();
using (OleDbCommand sqlCmd = new OleDbCommand(sqlText, con))
{
//execute command
result = sqlCmd.ExecuteNonQuery();
}
}
return result;
}
Resources:
ADO Features for each Release
Which Access file format should I use?
CREATE TABLE statement (Microsoft Access SQL)
System.Data.OleDb Namespace
The underwhelming answer to the problem is that my server was lacking some of the files my personal computer had, and only needed the correct files installed.
The missing piece in this case was the Microsoft Access Database Engine 2016 Redistributable, which I ended up finding here. Running that executable on my server got the needed files and everything worked after that.

SQL helper class - two connection strings

I have the following SQL helper class:
public class SqlHelper
{
SqlConnection cn;
public SqlHelper(string connectionString)
{
cn = new SqlConnection(connectionString);
}
public bool isConnection
{
get
{
if (cn.State == System.Data.ConnectionState.Closed)
cn.Open();
return true;
}
}
}
I also have two connection strings:
string connectionString = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", Variables.setDb1ServerName, Variables.setDb1Name, Variables.setDb1User, Variables.setDb1Password);
string connectionString2 = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", Variables.setDb2ServerName, Variables.setDb2Name, Variables.setDb2User, Variables.setDb2Password);
What I want to do is create two buttons that will check if the respective connection is active.
My attempt is below - button one:
private void txtConnection1_Click(object sender, EventArgs e)
{
string connectionString = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", Variables.setDb1ServerName, Variables.setDb1Name, Variables.setDb1User, Variables.setDb1Password);
try
{
SqlHelper helper = new SqlHelper(connectionString);
if (helper.isConnection)
MessageBox.Show("Конекцијата е успешна", "Порака", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Порака", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I've also create a second button, that connects to ConnectionString2 with SqlHelper helper2 = new SqlHelper(connectionString);
The code compiled alright. But I'm getting errors in the actual usage. One of the connections is diagnosed as active, while the second one produces a error.
Why question is.. can I reference two connection strings to a single sql helper class? If yes, any ideas where I might be making a mistake?
Update:
So this is the error that I am receiving. But if I restart the application and try the same connection first, I will be receiving a positive indicator.

#c Testbox to Database

Hello guys i've been stuck here for 2 days. I want when i full in my textboxes that the text will go to my database "loonberekening into my table werknemer".
But now im getting this
error: An unhandled exception of type 'System.ArgumentException'
occurred in System.Data.dll
Additional information: Keyword not supported: 'integra‌​ted security'.
and he is ticking this line: SqlConnection cnnLoonberekening = new SqlConnection(database);
Thanks for helping me and here is my code!
private void btnOpslaanwerknemergegevens_Click(object sender, EventArgs e)
{
string database = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\gip_stap_2\loonberekening.mdf;Integra‌​ted Security=True;Connect Timeout=30;InitialCatalog=loonberekening";
string werknemergegevens = "insert into loonberekening.werknemer (naam,voornaam) values ('"+this.txtNaam.Text+"','"+this.txtVoornaam.Text+"');";
SqlConnection cnnLoonberekening = new SqlConnection(database);
SqlCommand scmdLoon = new SqlCommand(werknemergegevens, cnnLoonberekening);
SqlDataReader check;
try{
cnnLoonberekening.Open();
check = scmdLoon.ExecuteReader();
MessageBox.Show("Opgeslagen");
while (check.Read())
{
}
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Please set the correct connection string like this
// SQL Connection String with |DataDirectory| substitution string
SqlConnection c = new SqlConnection (
#"Data Source=.; AttachDbFilename=|DataDirectory|\loonberekening.mdf;Initial Catalog=loonberekening");

cannot connect to oracle server from C#.net application

I'm trying to connect to remote Oracle server. My connection string -
OdbcConnection con = new OdbcConnection();
con.ConnectionString = #"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= xxxx)(PORT=xxxxx))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=abc.domain.com)));USER ID=user1;Password=pwd;";
I encountered error saying - "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified" (System.Data.Odbc.OdbcException) Exception Message = "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified", Exception Type = "System.Data.Odbc.OdbcException", Exception WinRT Data = ""
I specified my connection string according to my TNSNAMES.ora
Entry for my DB in TNSNAMES.ora goes like this:
DB.WORLD=
(DESCRIPTION=
(ADDRESS=
(PROTOCOL=TCP)
(HOST= xxxx)
(PORT=xxxxx)
)
(CONNECT_DATA=
(SERVER=dedicated)
(SERVICE_NAME=abc.domain.com)
)
)
Can someone explain on the error. Please help/suggest if my connection string went wrong and how to connect to Oracle server from my windows application
first install odp.net.managed using nuget packet manager:
Install-Package odp.net.managed
odp.net.managed work without preinstalled Oracle Client
next:
const string connectionString = #"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= xxxx)(PORT=xxxxx))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=abc.domain.com)));USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
if you have tnsnames.ora in application folder:
const string connectionString = #"Data Source=DB.WORLD;USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
or if tnsnames.ora in other folder:
Environment.SetEnvironmentVariable("TNS_ADMIN", #"path_to_tnsadmin.ora");
const string connectionString = #"Data Source=DB.WORLD;USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
you need to use OracleConnection
OracleConnection conn = new OracleConnection(connectionString);
download and install Oracle Data Provider for .NET
Go to Connections Strings for Oracle
Maybe will find some help
Use following Code:
using System;
using Oracle.DataAccess.Client;
class ConnectionSample
{
static void Main()
{
OracleConnection con = new OracleConnection();
//using connection string attributes to connect to Oracle Database
con.ConnectionString = "User Id=scott;Password=tiger;Data Source=oracle";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
// Close and Dispose OracleConnection object
con.Close();
con.Dispose();
Console.WriteLine("Disconnected");
}
}
Source ONE , TWO and THREE
Try something like this class :
public class OracleOperations
{
OracleConnection oraConn = new OracleConnection();
private bool connStatus;
public OracleOperations()
{
connStatus = false;
connect();
}
~OracleOperations()
{
disconnect();
}
public bool getConnStatus()
{
return connStatus;
}
public void connect()
{
string connString = "User Id=xxxx; Password=yyyyy; Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.10.10.10)(PORT=1583))(CONNECT_DATA=(SERVER=dedicated)(SID=oracledb)))";
if (oraConn.State != ConnectionState.Open)
{
try
{
oraConn.ConnectionString = connString;
oraConn.Open();
Console.WriteLine("Successful Connection");
connStatus = true;
}
catch (Exception eOra)
{
Console.WriteLine(eOra.Message+ "Exception Caught");
connStatus = false;
throw eOra;
}
}
}
public void disconnect()
{
if (oraConn.State == ConnectionState.Open)
{
try
{
oraConn.Close();
connStatus = false;
Console.WriteLine("Connection Closed");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "Exception Caught");
}
}
}
}
I would try Tnsping utility to make sure you can connect via tnsnames.ora
Try putting tnsnames.ora and sqlnet.ora in the same folder of the application and see if that addresses the issue.
With Managed ODP.Net there is one catch it does not support LDAP look up (e.g. LDAP.ora)
I'Ve Created an app.config File and configured the DB entry like this
<configuration>
<configSections>
<section name ="Environment" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<Environment>
<add key ="CIT" value ="Password=pwd123;User ID=abc123;Data Source=db1;Persist Security Info=True;Provider=MSDAORA"/>
<add key ="SIT" value ="Password=pwd234;User ID=abc234;Data Source=db2;Persist Security Info=True;Provider=MSDAORA"/>
<add key ="UAT" value ="Password=pwd345;User ID=abc345;Data Source=db3;Persist Security Info=True;Provider=MSDAORA"/>
</Environment>
</configuration>
Reffered that configuration into my form using ConfigurationManager(Need to refer the assembly - system.configuration). Add namespace - using System.Collections.Specialized to avail NameValueCollection. Code goes like this
environments = ConfigurationManager.GetSection("Environment") as NameValueCollection;
string strConnString = environments[envs];
conn = new OleDbConnection(strConnString);
conn.Open();
OleDbDataAdapter objDa = new OleDbDataAdapter("select * from tblABC", conn);
DataSet ds1 = new DataSet();
objDa.Fill(ds1); dataGridView1.DataSource = ds1.Tables[0];
Using datset, i've populated datagrid using an OleDbDataAdapter. It worked for my Windowsapplication.

SQL Connection with C#

TextBox1=Server Name
TextBox2=Db Name
TextBox3=User Name
TextBox4=Password
I declared as a variable "Server Name,dbname,user name,password".My question is; I want to test my sql connection on another machine by them using.
How can I do that with c#?
//// SqlConnection conn = new SqlConnection
////("Data Source="+ server +";Initial Catalog=DATA;Persist Security Info=True;User ID=sa");
You could use the SqlConnectionStringBuilder for this scenario:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = TextBox1.Text.Trim();
builder.InitialCatalog = TextBox2.Text.Trim();
builder.UserID = TextBox3.Text.Trim();
builder.Password = TextBox4.Text.Trim();
string result = builder.ConnectionString;
This builds up the connection string and returns it as a result in the end.
Also: you might want to use more descriptive names for your textboxes! tbxDataSource, tbxInitialCatalog etc. would be much better than TextBox1, TextBox2 etc.
little modified pranay's answer
bool TestConnection()
{
SqlConnection conn = new SqlConnection(string.Format(#"user id={0}; password={1};Data Source={2};
Trusted_Connection=yes;
Initial Catalog={3};
connection timeout=30", userName,password,serverName,database));
try
{
conn.Open();
return true;
}
catch (Exception e)
{
return false;
}
}

Categories