Database Access (C# vs Java)

    C# and Java use similar means for accessing database data. Both C# and Java require a database driver to perform the actual database operations. In addition, both require a database connection, a SQL query to execute against the database connection, and a result set from the execution of the query.  

Comparing Database Drivers
   Database drivers such as JDBC or ODBC can be used to access data in Java and C#. The Java Database Connectivity (JDBC) driver is used from a program written in Java. Open Database Connectivity (ODBC) is Microsoft's database programming interface for accessing a variety of relational databases on a number of platforms. There is also a JDBC-ODBC bridge standard on both the Solaris and Windows versions of the Java platform so you can also use ODBC from a Java program.
   In Java, the connection string information is supplied to the driver for a connection handle, as follows:

None.gif final static private String url = "jdbc:oracle:server,user,pass, …)";

   In C#, using the .NET Framework, you do not have to load ODBC or JDBC drivers in order to access the database. Simply set the connection string for the database connection object, as follows:

None.gif static string connectionString = "Initial Catalog=northwind;Data Source=(local);Integrated Security=SSPI;";
None.gifstatic SqlConnection cn = new SqlConnection(connectionString); 

 Java Read Database Example
   In Java, to perform a database read operation, you can use a ResultSet object created by the executeQuery method of the Statement object. The ResultSet object contains the data returned by the query. You can then iterate through the ResultSet object to access the data.
   The following example provides the Java code to read from a database.

None.gif Connection c;
None.giftry
None.gif{
None.gif    Class.forName (_driver);
None.gif    c = DriverManager.getConnection(url, user, pass);
None.gif
None.gifcatch (Exception e) 
None.gif{
None.gif    // Handle exceptions for DriverManager
None.gif    // and Connection creation:
None.gif}
None.giftry
None.gif{
None.gif    Statement stmt = c.createStatement();
None.gif    ResultSet results = stmt.executeQuery(
None.gif                "SELECT TEXT FROM dba ");
None.gif    while(results.next())
None.gif    {
None.gif        String s = results.getString("ColumnName");
None.gif        // Display each ColumnName value in the ResultSet:
None.gif    }
None.gif    stmt.close();
None.gif
None.gifcatch(java.sql.SQLException e)
None.gif{
None.gif    // Handle exceptions for executeQuery and getString: 
None.gif}
None.gif

   Similarly, to perform a database write operation, a Statement object is created from the Connection object. The Statement object has methods for executing SQL queries and updates against a database. Updates and queries are in the form of a string containing the SQL command of a write operation used in the executeUpdate method of the Statement object to return a ResultSet object.


C# Read Database Example
   In C#, using the .NET Framework, accessing data is further simplified through the set of classes provided by ADO.NET, which supports database access using ODBC drivers as well as through OLE DB providers. C# applications can interact with SQL databases for reading, writing, and searching data using.NET Framework's ADO.NET classes, and through a Microsoft Data Access Component ( MDAC). The .NET Framework's System.Data.SqlClient namespace and classes make accessing SQL server databases easier.

In C#, to perform a database read operation, you can use a connection, a command, and a data table. For example, to connect to a SQL Server database using the System.Data.SqlClient namespace, you can use the following:

The .NET Framework provides the DataAdapter, which brings these three objects together, as follows:

  • The SqlConnection object is set using the DataAdapter object's connection property.

  • The query to execute is specified using the DataAdapter's SelectCommand property.

  • The DataTable object is created using the Fill method of the DataAdapter object. The DataTable object contains the result set data returned by the query. You can iterate through the DataTable object to access the data rows using rows collection.

To compile and run the code, you need the following; otherwise, the line databaseConnection.Open(); fails and throws an exception.

  • Microsoft Data Access Components (MDAC) version 2.7 or later.

    If you are using Microsoft Windows XP or Windows Server 2003, you already have MDAC 2.7. However, if you are using Microsoft Windows 2000, you may need to upgrade the MDAC already installed on your computer. For more information, see MDAC Installation.

  • Access to the SQL Server Northwind database and integrated security privileges for the current user name running the code on a local SQL Server with the Northwind sample database installed.

    None.gif // Sample C# code accessing a sample database
    None.gif
    None.gif// You need:
    None.gif//   A database connection
    None.gif//   A command to execute
    None.gif//   A data adapter that understands SQL databases
    None.gif//   A table to hold the result set
    None.gif
    None.gifnamespace DataAccess
    None.gif{
    None.gif    using System.Data;
    None.gif    using System.Data.SqlClient;
    None.gif
    None.gif    class DataAccess
    None.gif    {
    None.gif        //This is your database connection:
    None.gif        static string connectionString = "Initial Catalog=northwind;Data Source=(local);Integrated Security=SSPI;";
    None.gif        static SqlConnection cn = new SqlConnection(connectionString); 
    None.gif
    None.gif        // This is your command to execute:
    None.gif        static string sCommand = "SELECT TOP 10 Lastname FROM Employees ORDER BY EmployeeID";
    None.gif
    None.gif        // This is your data adapter that understands SQL databases:
    None.gif        static SqlDataAdapter da = new SqlDataAdapter(sCommand, cn);
    None.gif
    None.gif        // This is your table to hold the result set:
    None.gif        static DataTable dataTable = new DataTable();
    None.gif
    None.gif        static void Main()
    None.gif        {
    None.gif            try
    None.gif            {
    None.gif                cn.Open();
    None.gif
    None.gif                // Fill the data table with select statement's query results:
    None.gif                int recordsAffected = da.Fill(dataTable);
    None.gif
    None.gif                if (recordsAffected > 0) 
    None.gif                {
    None.gif                    foreach (DataRow dr in dataTable.Rows)
    None.gif                    {
    None.gif                        System.Console.WriteLine(dr[0]);
    None.gif                    }
    None.gif                }
    None.gif            }
    None.gif            catch (SqlException e) 
    None.gif            {
    None.gif                string msg = "";
    None.gif                for (int i=0; i 
    <  e .Errors.Count; i++)
    None.gif                {
    None.gif                    msg +
    = "Error #"  + i + " Message: " + e.Errors[i].Message + "\n";
    None.gif                }
    None.gif                System.Console.WriteLine(msg);
    None.gif            }
    None.gif            finally
    None.gif            {
    None.gif                if (cn.State !
    = ConnectionState.Closed)
    None.gif                
    {
    None.gif                    cn.Close();
    None.gif                }
    None.gif            }
    None.gif        }
    None.gif    }
    None.gif}
    None.gif
    None.gif




转载于:https://www.cnblogs.com/longb/archive/2006/04/10/371459.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值