Java实现JDBC连接数据库实例

时间:2021-07-28 09:41:02
 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class JDBCTest { private static final String URL="jdbc:mysql://127.0.0.1:3306/student";
private static final String USER="root";
private static final String PASSWORD="root"; public static void main(String[] args) throws ClassNotFoundException, SQLException { //1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver"); //2.获得数据连接
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD); //3.使用数据库的连接创建声明
Statement stmt = conn.createStatement(); //4.使用声明执行SQL语句
ResultSet rs = stmt.executeQuery("select * from stu"); //5.读取数据库的信息
while(rs.next()){
String id = rs.getString("id");
String name = rs.getString("name");
String sex = rs.getString("sex");
String score = rs.getString("score");
System.out.println(id+"姓名:"+name+",性别:"+sex+",成绩:"+score);
} } }