What is the connection string for odbc connections? - asp.net

I've always done web apps and now I need to do a console app. I need to use both an odbc connection and a regular connection.
In the past I would have used:
<add name="LinkConnectionString" connectionString="Data Source=SERENITY\SQLEXPRESS;Initial Catalog=Link;Integrated Security=True" providerName="System.Data.SqlClient"/>
In the web.config, however I am not sure how to do the same thing with inline code.
So like string connectionString = #".....";
I have tried multiple combinations, looked online (including connectionstrings.com), but none of them worked.
Can anyone help me out? I want both the odbc and the regular... as they seem different should be different according to the sample ones online (that don't work).

A cool trick to building connection strings is to right click on your desktop, choose "new text document" - this will make a temporary notepad .txt file. Rename it to .udl and then double click it - you can now create any connection string. Click ok when done and open the file in notepad to see the connectionstring.
UPDATED April 28, 2009 (powershell script):
function get-oledbconnection ([switch]$Open) {
$null | set-content ($udl = "$([io.path]::GetTempPath())\temp.udl");
$psi = new-object Diagnostics.ProcessStartInfo
$psi.CreateNoWindow = $true
$psi.UseShellExecute = $true
$psi.FileName = $udl
$pi = [System.Diagnostics.Process]::Start($psi)
$pi.WaitForExit()
write-host (gc $udl) # verbose
if (gc $udl) {
$conn = new-object data.oledb.oledbconnection (gc $udl)[2]
if ($Open) { $conn.Open() }
}
$conn
}

You should be able to find whatever you need here:
http://www.connectionstrings.com/
For one of our apps we use this connection string:
"DRIVER={driver};SERVER=server.database;UID=username;PWD=password"

I think it deppends as to what database you want to connect, because of the Driver that its used to connect to the database engine.
You might want to take a look at:
http://www.connectionstrings.com/
They have plenty of examples there.

Have you tried something like this for SQLServer?
SqlConnection conn = new SqlConnection(#"Data Source=SERENITY\SQLEXPRESS;Initial Catalog=Link;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM tableName", conn);
conn.Open();
//<snip> Run Command
conn.Close();
and this for ODBC
OdbcConnection conn = new OdbcConnection(#"ODBC connection string");
OdbcCommand cmd = new OdbcCommand("SELECT * FROM tableName", conn);
conn.Open();
//Run Command
conn.Close();

<add name="myName" connectionString="dsn=myDSN;UID=myUID;"
providerName="System.Data.Odbc" />

Related

How can i design my asp.net-oracle configuration?

I'm working on a asp.net project. I'm gonna use oracle db. I've started to design my database class(for connection and sql command operations). I know how i will write connection or query section and functions (i used ado.net with ms sql before and i remember that was easyer on mssql) But i have some problems about the first operations. I dont know if i need to design in web config(if i need, i dont know how to do it). And i dont know whats my connection string. There are somethings on web that i found but i couldnt get it. I'm using oracle sql developer (purple icon). I looked for something about my connection string on the tool. But i'm not used to using oracle.
You can use 2 ways ,however first method is obsoleted not recommended to use
Method:1 Under web.config of your asp.net you can use below code
<appSettings>
<!--Development String-->
<add key="CustomerDataConnectionString" value="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=server_address)(PORT=Port_Number))(CONNECT_DATA=(SID =SessionID)));User Id=***;Password=***;"/>
</appSettings
//in asp.net code file access that using below way
static string strConnectionString = ConfigurationSettings.AppSettings["CustomerDataConnectionString"].ToString();
Method:2
<connectionStrings>
<add name="CustomerDataConnectionString" connectionString="Data Source=server_db_address;User Id=***;Password=***;Integrated Security=SSPI;Initial Catalog=Northwind;OLEDB.NET=True" providerName="OraOLEDB.Oracle"/>
</connectionStrings>
string strConnectionString = ConfigurationManager.ConnectionStrings["CustomerDataConnectionString"].ConnectionString;
//Common code for both the method in Database layer
DataTable table = null;
using (OracleConnection con = new OracleConnection(strConnectionString))
{
using (OracleCommand cmd = con.CreateCommand())
{
cmd.CommandType = cmdType;
cmd.CommandText = commandName;
try
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
using (OracleDataAdapter da = new OracleDataAdapter(cmd))
{
table = new DataTable();
da.Fill(table);
}
}
catch (Exception ex)
{
throw ex;
}
}
}

SQL Server connection for ALTER LOGIN c# .net

This c# code just doesn't want to change Password on the server (UserID and PW will obviously be a strings for some purpose, but this is just to get it working):
SqlConnection conn = new SqlConnection ("Data Source=ServerIP;Persist Security Info=False;User ID=UserID;Password=UserPW");
SqlCommand cmd = new SqlCommand ("ALTER LOGIN UserID WITH PASSWORD='NewPW' OLD_PASSWORD='UserPW'", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
conn.Close();
Changing Password using the same command ALTER LOGIN UserID WITH PASSWORD='NewPW' OLD_PASSWORD='UserPW' with a Server Management studio works like a charm, so there is no problem within command line or/and permissions for this particular User.
I guess I miss something in Sql Connection line.
Already tried combinations of:
Initial Catalog=master;
Initial Catalog=;
Integrated Security=SSPI;
Persist Security Info=True;
Changing command type, using ExecuteNonQuery();, and many other things, but nothing seems to work.
"Google" doesn't give any valuable result, hopefully I will find my answer here, thanks for taking your time in advance.
Try the following, works a treat for me:
SqlConnection conn = new SqlConnection ("Data Source=ServerIP;Persist Security Info=False;User ID=UserID;Password=UserPW");
SqlCommand cmd = new SqlCommand ("ALTER LOGIN UserID WITH PASSWORD='NewPW' OLD_PASSWORD='UserPW'", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
You forgot to put cmd.ExecuteNonQuery() after you opened the connection. I just tested this and it successfully changed the password on my local database.
string queryString = #"DECLARE #sql NVARCHAR(500)
SET #sql = 'ALTER LOGIN ' + QuoteName(#loginName) +
' WITH PASSWORD= ' + QuoteName(#password, '''')
EXEC #sql ";
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#loginName", loginName);
command.Parameters.AddWithValue("#password", password);
connection.Open();
command.ExecuteNonQuery()
}
UPDATE
With DDL (data definition language) statements (as ALTER LOGIN) you cannot use parameters directly. That's why I'm using a dynamic SQL.
The QuoteName will do proper quoting in the SQL, simply doubles any [ characters (first call) or ' characters (second call).

Unable to retrieve values from database in asp.net

I am doing first asp.net app, now need to connect it to SQL (Using MS SQL 2008), but I am unable to get any value from the tables.
My web.config is:
<add name="MainConnectString" connectionString="Data Source=LUCKYY-PC;initial catalog=testDbName;uid=sa;Password=123456;Integrated Security=True" providerName="System.Data.SqlClient" />
In backend Code:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MainConnectString"].ConnectionString))
{
string query = "select * from [testTableName]";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
string numRows = cmd.ExecuteScalar().ToString();
SqlDataAdapter da = new SqlDataAdapter(query, conn);
DataSet ds = new DataSet();
da.Fill(ds);
dataGrid.DataSource = ds;
conn.Close();
}
dataGrid is the datagrid name i have defined on ascx page of this code.
but 'ds' appears with 0 count, and so the datagrid is blank, I don't know if I am missing anything on code or in web.config ...any help will be appreciated
dataGrid.DataBind() - filled the datagrid, thanks Mohsen
Check your connection string. I think you had make mistake in writing data source, I think you are using SQL server 2005/2008/2008 R2, and so data source must be to set as .(DOT) or localhost. Try this one may be it can help you.....
There were two problems in your code:
As #ethorn10 commented, ExecuteScalar() as you are using it won't give you what you expecting. Change your query to:
string query = "select count(*) from [testTableName]";
You have forgotten to call the datagrid DataBind() method to show the records selected from datasource.
dataGrid.DataSource = ds;
dataGrid.DataBind();
If you are new to asp.net, I strongly recommend you to learn and use Entity framework instead of using the old ADO.net code like yours.

How to set database with AdomdConnection

When I execute this code:
AdomdConnection con = new AdomdConnection("Data Source=MyServer;User ID=MyDomain\\MyUserName;Password=MyPassword");
con.Open();
con.ChangeDatabase("Analysis Services Project1");
I get this exception:
Either the user, MyDomain\MyUserName$, does not have access to the
Analysis Services Project1 database, or the database does not exist.
The database name comes from looking at the server using Microsoft SQL Server Management Studio. If I bring up the properties on the server and go to the security section, my account is listed as a Server administrator. While in management studio, I can see data sources, cubes and execute mdx queries fine.
Why can't do I get this exception in code?
whihc line causes the error?
I imagine you have to infor the catalog on your connection string. Try addind
Catalog=Analysis Services Project1
to your con string.
Also, Analysis Services Project1 seems to be the projects name? Are you sure this is the database name as well?
First
added the reference for Microsoft.AnalysisServices.AdomdClient.dll
strCon = "Data Source=DBserverServerName;Integrated Security=SSPI;Initial Catalog=DBName;";
AdomdConnection con = new AdomdConnection("connectionstring"); // connect DB con.Open(); AdomdCommand cmd = new AdomdCommand("MDX query", con); //query
AdomdDataReader reader = cmd.ExecuteReader(); //Execute query
while (reader.Read()) // read
{
Data dt = new Data(); // custom class
dt.Gender = reader[0].ToString();
dt.Eid = reader[1].ToString();
dt.salary = reader[2].ToString();
data.Add(dt);
}

how do i connect to oracle with the info i have?

i have the info below from the oracle DBA and want to connect to oracle from a .net application. i just got done installing the oracle tools/ drivers for windows/ .net and now want to get a console app to connect tot he oracle DB and extract data from oracle into SQL server.
another solution would be to have SQL server pull from oracle all the records in the bugs table. i have no clue what the oracle connection string is and have tried to create a system DSN but failed at that prior to turning to the SO gurus...
ORACLE SQL user name is ‘USER_dev’,
password is ‘welcome’.
Connection string is
‘jdbc:mercury:oracle://qct-ds2-p.apps.com:1139;sid=QCTRP1’
i got lucky and found a simple solution that is all in .net and requires nothing more than this syntax by way of a connection string. all the .ora stuff is presented in the connection string and works well.
static void getData()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
//Console.WriteLine("State: {0}", connection.State);
//Console.WriteLine("ConnectionString: {0}", connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM BUG";
//string sql = "SELECT table_name FROM user_tables";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//string myField = (string)reader["Project"];
string myField = (string)reader[0];
Console.WriteLine(myField);
}
}
}
static private string GetConnectionString()
{
return "User Id=USER_dev;Password=welcome;Data Source=(DESCRIPTION=" +
"(ADDRESS=(PROTOCOL=TCP)(HOST=111.123.479.24)(PORT=1139))" +
"(CONNECT_DATA=(SID=QCTRP1)));";
}
go into your ORACLE_HOME\network\admin directory. Create a file called tnsnames.ora if it is not there already. Add this into it:
QCTRP1.WORLD =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = qct-ds2-p.apps.com)(PORT = 1139))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = QCTRP1)
)
)
I'm making some assumptions here...
does qct-ds2-p.apps.com resolve?
looks like the DBA set it up the listener on port 1139... default is normally 1521 so you'll need to confirm.
You can then set up a connection string as follows:
Connection conn = DriverManager.getConnection
("jdbc:oracle:oci8:#QCTRP1.WORLD", "dev", "welcome");
now that you have the tnsnames created from #erbsock, you will need to get the .net side of
things working. Oracle has several tutorials available to help you in this matter.
When you install the Oracle ODP (in the link you will see samples as well as the downloads) drivers you will get a directory created in the
%oracle_home%\odp.net\samples\4\DataSet\DSPopulate\src
(this appears to be the same example as located # http://www.oracle.com/technology/sample_code/tech/windows/odpnet/DSPopulate/ViewProducts.cs.html)
as an initial test I would recommend just changing around the id/passwrd/sql/etc and trying it out.
it is not that fundamentally different than using System.Data; but there are a few gotchas and remember that each computer will need to have ODP/Oracle client installed to have them work with the ora connection.
if you have any problems post the exact error msg that is displayed as well as a snippet of your .net code that establishes the connection, does the query, and where it is breaking

Resources