Java连接mysql数据库并实现增删改查

1.创建java项目并导入jar包
mysql-connector-java-5.1.9-bin.jar
链接:https://pan.baidu.com/s/1p-e9U2WUr4cPglXpoILOxA
提取码:g829
2.建立 test 数据库并创建表 student
在这里插入图片描述
student表定义如下
student表
3.编写实现代码


public class SqlCon {

    private static final String DRIVER = "com.mysql.jdbc.Driver"; //驱动程序名
    private static final String URL = "jdbc:mysql://localhost:3306/test"; //数据库的路径
    private static final String USER = "root"; //用户名
    private static final String PASSWORD = "123456"; //密码
    Connection connection=null;
    Statement statement=null;
    ResultSet rs=null;


     //在构造方法中为conn对象实例化,取得数据库的连接对象
    public SqlCon() throws SQLException, ClassNotFoundException {

        try {
            Class.forName(DRIVER); //加载驱动程序

            connection = DriverManager.getConnection(URL, USER, PASSWORD); //连接数据库

            statement=connection.createStatement();

        }catch (Exception e){
            e.printStackTrace();
        }
        }

        //查
        public void query(String tableName) throws SQLException {
            String sql = "select * from "+tableName; // 要执行的SQL语句
            ResultSet rs = statement.executeQuery(sql);// ResultSet类,用来存放获取的结果集
            int sid = 0;
            String sname = null;
            while (rs.next()) {
                sid = rs.getInt("sid");// 获取id这列数据
                sname = rs.getString("sname");// 获取id这列数据
                System.out.println(sid + ":" + sname);// 输出
            }
        }

        //增
        public void insert(String tableName,int sid,String sname) throws SQLException {
            String sql = "insert into "+tableName+" values("+sid+",'"+sname+"');";
            statement.executeUpdate(sql);
        }

        //删
        public void delete(String tableName,int sid) throws SQLException {
        String sql = "delete from "+tableName+" where sid="+sid;
        statement.executeUpdate(sql);
        }

        //改
        public void update(String tableName,int sid,String sname) throws SQLException {
        String sql = "update student set sname='"+sname+"' where sid="+sid;
        statement.executeUpdate(sql);
        }

        //关闭数据库
        public void close() {
            if (connection != null) { //表示现在有连接对象
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        SqlCon sqlCon=new SqlCon();
//        sqlCon.insert("student",9,"cz");
//       sqlCon.delete("student",6);
//       sqlCon.update("student",5,"cd");
        sqlCon.query("student");
//        sqlCon.close();

    }
}

4.运行截图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值