数据库、连接、输入输出,jdbcAccess类

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();
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值