准备条件:
1、JDBC jar包(在这里有)
2、wampserver用来做服务器
过程:
1、加载驱动,首先在加载之前要将jar包导入,在工程目录下面新建一个lib文件夹,将jar包放在lib中,然后将jar包导入到工程中,这就不做详细说明。利用Class.forName方法加载驱动。
2、连接数据库,基本就是一个固定格式,中间要说明连接什么数据库,服务器地址,端口号,数据库名,用户名,密码。
3、输出一个对象说明连接成功。
4、执行一个查询语句,保存到一个数据对象中,然后根据数据库的列属性来获取其中的数据。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Main { public static void main(String[] args) throws ClassNotFoundException, SQLException { //1 加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2 获得数据库的连接 Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", ""); System.out.println(con); //3 String sql = "select * from student"; PreparedStatement pst = con.prepareStatement(sql); ResultSet rst = pst.executeQuery(); //执行查询语句的方法,返回的类似一个数组 while(rst.next()){ int id = rst.getInt("id"); String name = rst.getString("name"); int age = rst.getInt("age"); System.out.println(id+"---"+name+"---"+age); } rst.close(); pst.close(); con.close(); } }