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

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;
}
}
}

Related

How to use SQL-Server Stored Procedures?

over the past week or so I've been building an ASP site that connects to a Sql-Server 2008 database. I've never used Stored procedures and I was wondering if anyone could give me some guidance on how to create and how to use them within an ASP method. I'm trying to make the code of the website as simple and elegant as possible. Here's the code I'm trying to change into a stored procedure:
private void ExecuteInsert(string name, string type)
{
SqlConnection conn = new SqlConnection(GetConnectionStringHM());
string sql = "INSERT INTO tblSoftwareTitles (SoftwareName, SoftwareType) VALUES "
+"(#SoftwareName,#SoftwareSystemType)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[2];
//param[0] = new SqlParameter("#SoftwareID);
param[0] = new SqlParameter("#SoftwareName", SqlDbType.NVarChar, 200);
param[1] = new SqlParameter("#SoftwareType", SqlDbType.Int);
param[0].Value = name;
param[1].Value = type;
for (int i= 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg ="Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
This is just a Simple insert that takes two parameters from an entry form and inserts them into the database. Any Help with this would be much appreciated as I feel it would be a useful thing to know later on down the line. Thanks in advance!
You should look in to MSDN basics: http://msdn.microsoft.com/en-us/library/bb896274.aspx
You don't need to complicate things using for loop.
try
{
sqlConnection = new SqlConnection(dbConnectionString);
SqlCommand command = new SqlCommand(sql, sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#SoftwareName", SqlDbType.NVarChar, 200).Value = SoftwareNameHere;
command.Parameters.Add("#SoftwareType", SqlDbType.Int).Value = SoftwareTypeHere;
sqlConnection.Open();
return command.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine("SQL Error" + ex.Message.ToString());
return 0;
}
finally
{
conn.Close();
}
If you are using .NET 3.5 or above, you can use the USING code block which takes care of the disposal of your resources. I am not entirely sure, but from what I remember this was introduced with .NET 3.5 to replace Try/Finally code block (which required developers to dispose the resources like connection object manually through code).
using (SqlConnection con = new SqlConnection { dbConnectionString })
{
con.Open();
try
{
using (SqlCommand command = new SqlCommand { CommandType = CommandType.StoredProcedure, Connection = con, CommandTimeout = 300, CommandText = "sp_Test" })
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#SoftwareName", SqlDbType.NVarChar, 200).Value = SoftwareNameHere;
command.Parameters.Add("#SoftwareType", SqlDbType.Int).Value = SoftwareTypeHere;
command.ExecuteNonQuery();
}
}
catch(SqlException ex)
{
//ex.ToString message here;
}
}
The answer you're looking for is at this SO post...
https://stackoverflow.com/a/4561443/1246574
The one thing I would improve upon for the accepted answer in that post, is the example in that answer doesn't use any USING statements. It would be better to have the connection and command within USING statements so they are automatically disposed.
Another approach would be to use the Microsoft Enterprise Library for interacting with your SQL Server DB. I think it's easier than using plain old SqlConnection and SqlCommand.
Since your code already uses parameters, you are 90% of the way there. All you have to do is:
Put the insert statement into a stored procedure, keeping the same parameter definitions as the dynamic statement.
Change CommandType.Text to CommandType.StoredProcedure
Change the command text to be just the name of the stored procedure.
Having done some reading on the subject I've come across some useful articles that really do question my need for stored procedures.
This article gives a good Viewpoint on how stored procedures can be more of a hassle than a help and are quite clunky and tedious in terms of coding, debugging ad error reporting.
http://www.codinghorror.com/blog/2004/10/who-needs-stored-procedures-anyways.html
And this article (linked in the one above) gives a good explanation on parametrized, explaining why they are necessary to reduce the risk of sql injections and also raises the point that these parametrized queries are cached in a similar way to procedures, giving them comparable performance gains
http://www.uberasp.net/getarticle.aspx?id=46
I feel that In my situation keeping parametrized sql Queries coded into my ASP pages will be the smartest move as these pages will be stored on a server and accessed by clients. I imagine if this were an application installed on several client machines hard coding the SQL wouldn't be a desirable option and so Stored procedures would be the best way to go (to my knowledge)
A follow Up to Stored procedures verses Parametrized sql can be found here with different links to each side of the argument if those are interested.
http://www.codinghorror.com/blog/2005/05/stored-procedures-vs-ad-hoc-sql.html
Hope this little answer helps out anyone else considering using stored procedures over parametrized SQL and vice-versa

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.

using SqLite in Asp.Net

I'm trying to use SqLite in my Asp.Net. I have the code below in connectionstring web.config
<add name="ConnectionStringName" connectionString="data source=MembersLastLogin3.s3db" providerName="System.Data.SQLite" />
and here is the code for running query
public int ExecuteNonQuery(string sql)
{
try
{
string con = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
SQLiteConnection cnn = new SQLiteConnection(con);
cnn.Open();
SQLiteCommand mycommand = new SQLiteCommand(cnn);
mycommand.CommandText = sql;
int rowsUpdated = mycommand.ExecuteNonQuery();
cnn.Close();
return rowsUpdated;
}
catch { throw; }
}
}
and this simple query
sql = "INSERT INTO LastLogin (MemId ) VALUES ('" + res + "');";
LocalDb.ExecuteNonQuery(sql);
but I get the error "Table LastLogin doesn't exist"
I have used SqLitein .Net already but it's the first time I'm using it in Asp.Net,I'm sure the table exists but it seems it can connect to it, where is my problem? is the setting in web.config is enough? is there any tutorial available ? thanks
I suppose your file db is stored in App_Data directory of the asp.net website.
So just try to change your connection string with:
<add name="ConnectionStringName" connectionString="data source=|DataDirectory|MembersLastLogin3.s3db" providerName="System.Data.SQLite" />
Verify if the table(s) exist in your SQLite db using the GetSchema method:
using ( var conn = new SQLiteConnection( "Data Source=<PathToDb>\\MembersLastLogin3.s3db" ) )
{
DataTable tbl = conn.GetSchema("Tables")
// The DataTable will list all the tables in the
// db as well as information about each table.
}
The most likely cause is the connection string you are using is not pointing to the SQLite database which is why you'll see the error table does not exist.
As a side note regarding the sample code you posted, if you are not doing anything with the exception, then there is no need to try/catch the exception if the exception is just going to be thrown back.
Edit: Looks like you need to specify an absolute path: SQLite accessed by code has no tables?

What is the alternative for System.Data.OracleClient.OracleCommand?

Can anyone share a link to sample (ASP).Net code that uses the new Oracle Data Provider.Net library?
I have code a web application code that uses the System.Data.OracleClient classes and want to migrate to the new Oracle Data Provider for .Net.
Thanks
Your code might look as any standard ADO.NET code and you will be using an OracleConnection:
var connectionString = "Data Source=ORCL;User Id=user;Password=pwd;";
using (var conn = new OracleConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT name FROM mytable";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string name = reader.GetString(0);
// TODO: process the results here
}
}
}
There is no real difference in how they are used, unless you are doing weird stuff with In/Out parameters or cursors.
The difference that you would see in your code is that the namespace will change to Oracle.DataAccess. I believe that most of the type-names stayed the same.

What is the connection string for odbc connections?

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" />

Resources