首页 > 代码库 > Java中的JDBC_part1

Java中的JDBC_part1

简介

JAVA程序想要对数据库进行访问,需要有JDBC驱动程序的支持。JDBC驱动程序提供了对各种主流数据库的接口,程序员只需要学习掌握这一套接口,就可以实现对所有数据库的访问代码编写。

一般步骤

  1. JAVA访问数据库一般分为以下步骤
  2. 加载JDBC驱动程序
  3. 创建对数据库的连接
  4. 执行SQL语句
  5. 获取执行结果并对其处理
  6. 关闭连接资源

示例代码:

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

 

 

public class Hello

{

       static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

       static final String DB_URL = "jdbc:mysql://localhost:3306/mldn";

       static final String USERNAME = "root";

       static final String PASSWORD = "admin";

      

    public static void main(String a[]) 

    {

       Connection conn = null;

       Statement stmt = null;

       ResultSet rs = null;

       try

              {

              //加载驱动

                     Class.forName(JDBC_DRIVER);

                     //获取链接

                     conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);

                     //执行SQL语句

                     stmt = conn.createStatement();

                     rs = stmt.executeQuery("SELECT name FROM user;");

                     //获取结果

                     while(rs.next())

                     {

                           System.out.println("Hello " + rs.getString("name"));

                     }

              }

       //异常处理

       catch (ClassNotFoundException e)

              {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              } catch (SQLException e)

              {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }

       finally

       {

              //资源清理

                     try

                     {

                           conn.close();

                           stmt.close();

                           rs.close();

                     }

                     catch(Exception e)

                     {

                           //ignore exceptions when closing.

                     }

              }

      

    } 

}

 

Java中的JDBC_part1