package Ex11;
import java.sql.*;
public class JdbcAccess {
public JdbcAccess(){}
Connection con; // 声明Connection对象
public static String user;
public static String password;
public Connection getConnection() { // 建立返回值为Connection的方法
try { // 加载数据库驱动类
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("数据库驱动加载成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
user = "root";//数据库登录名
password = "cgy123";//密码
try { // 通过访问数据库的URL获取数据库连接对象
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/CJGL?useUnicode=true&characterEncoding=gbk", user, password);
System.out.println("数据库连接成功");
} catch (SQLException e) {
e.printStackTrace();
}
return con; // 按方法要求返回一个Connection对象
}
public void getStudent() throws SQLException {
//执行SQL对象Statement,执行SQL的对象
Statement statement = con.createStatement();
String sql = "SELECT *FROM student;";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("===========");
System.out.println("stuid="+resultSet.getString("stuid"));
System.out.println("name="+resultSet.getString("name"));
System.out.println("score="+resultSet.getString("score"));
}
}
public void addStudent(String stuid,String stuname,int score) throws SQLException {
//执行SQL对象Statement,执行SQL的对象
Statement statement = con.createStatement();
String sql = "insert into student(stuid,name,score) values("+"'"+stuid+"'"+","+"'"+stuname+"'"+","+score+");";
System.out.println(sql);
statement.execute(sql);
}
}
package Ex11;
public class Demo {
public static void main(String[] args) throws Exception {
JdbcAccess j =new JdbcAccess();
j.getConnection();
j.addStudent("105","xiaoyang",88);
j.getStudent();
}
}