工具:Eclipse 、mysql5.7
MySQL连接驱动:mysql-connector-java-5.1.27.jar 获取地址:https://dev.mysql.com/downloads/connector/j/
加载驱动:
1.在工程目录中创建lib文件夹,将下载好的mysql连接驱动放到该文件夹下
2.右键工程名,在java build path中的Libraries分页中选择Add JARs...,选择刚才添加的jar包,如下图:
3.安装mysql,设置了连接端口、用户名、密码
4.使用Navicat工具连接上mysql并创建数据库sqltestdb和数据表emp
5.java连接数据库并读取数据
package sqldemo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DemoMain{ public static void main(String[] args){ Connection con; String driver="com.mysql.jdbc.Driver"; String url="jdbc:mysql://localhost:3308/sqltestdb?useSSL=false"; String user="root"; String password="root"; try{ Class.forName(driver); con=DriverManager.getConnection(url, user, password); if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); Statement statement=con.createStatement(); String sql="select * from myTable"; ResultSet rs=statement.executeQuery(sql); System.out.println("姓名"+" "+"职位"+" "+"年龄"); System.out.println("--------------------------------------"); String mWork=null; String mName=null; String mAge=null; while(rs.next()){ mWork=rs.getString("mWork"); mName=rs.getString("mName"); mAge=rs.getString("mAge"); System.out.println(mName+" "+mWork+" "+mAge); } rs.close(); con.close(); }catch(ClassNotFoundException e){ System.out.println("The driver can't be found!"); e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally{ System.out.println("Success!"); } } }