连接数据库是我们开发信息管理系统最基本的操作,因为我们管理信息系统的业务数据都是放在数据库里存储的。市面上数据库的种类有很多,比如常用的数据库有SQLServer,Oracle,MySQL等。今天我们就用MySQL数据库为例子,讲解一下JDBC是如何连接MySQL的。本篇的知识很基础,主要是个一些刚学JAVA的同学演示一下,让他们知道连接JDBC的基本流程。
JDBC连接MySQL数据库代码如下:
import java.sql*; public class TestJDBC { public static void main(String[] args) { Connection conn=null; Statement stmt=null; ResultSet rs=null; String sql="select * from student"; try { //1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2.连接mysql数据库 conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","1234567"); //3.通过数据库的连接操作数据库,实现增删改查 stmt=conn.createStatement(); rs=stmt.executeQuery(sql); while(rs.next()) { System.out.println(rs.getInt("id")+","+rs.getString("name")+","+rs.getInt("age")); } }catch(ClassNotFoundException e) { e.printStackTrace(); }catch(SQLException e) { e.printStackTrace(); }finally { try { if(rs!=null) { rs.close(); } if(stmt!=null) { stmt.close(); } if(conn!=null) { conn.close(); } }catch(SQLException e) { e.printStackTrace(); } } } }总结:
以上就是JDBC连接mysql数据库的例子,实现的代码很简单。第一步主要是先加载com.mysql.jdbc.Driver驱动,然后是连接数据库,这边要注意mysql数据库的地址要拼写正确,同时要传入正确的mysql数据库账号和密码。连接成功以后就可以进行正常的数据库增删查改操作啦。