Java开发——JDBC的使用

来源:互联网 发布:淘宝10.11事变结果 编辑:程序博客网 时间:2024/06/06 07:17

  JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。

  使用JDBC连接MySQL数据库:

 

  Class.forName("com.mysql.jdbc.Driver");  Connection connection = null;  connection = DriverManager.getConnection(          "jdbc:mysql://hostname:port/dbname","username", "password");  connection.close();
 

  使用JDBC的完整样例:

 

package com.mkyong.common; import java.sql.DriverManager;import java.sql.Connection;import java.sql.SQLException; public class JDBCExample { public static void main(String[] argv) { System.out.println("-------- MySQL JDBC Connection Testing ------------"); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is your MySQL JDBC Driver?");e.printStackTrace();return; } System.out.println("MySQL JDBC Driver Registered!");Connection connection = null; try {connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mkyongcom","root", "password"); } catch (SQLException e) {System.out.println("Connection Failed! Check output console");e.printStackTrace();return;} if (connection != null) {System.out.println("You made it, take control your database now!");} else {System.out.println("Failed to make connection!");}}}

运行后,结果如下:

C:\test>java -cp c:\test\mysql-connector-java-5.1.8-bin.jar;c:\test JDBCExample-------- MySQL JDBC Connection Testing ------------MySQL JDBC Driver Registered!You made it, take control your database now! C:\test>

JDBC(以及MySQL与其他语言连接的API)地址 http://dev.mysql.com/downloads/connector/j/