标签:
JAVA程序想要对数据库进行访问,需要有JDBC驱动程序的支持。JDBC驱动程序提供了对各种主流数据库的接口,程序员只需要学习掌握这一套接口,就可以实现对所有数据库的访问代码编写。
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. } }
} }
|
标签:
原文地址:http://www.cnblogs.com/kuillldan/p/5863947.html