java链接数据库,增删改查用法

 package test2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.mysql.jdbc.PreparedStatement;

public class D {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // TODO Auto-generated method stub
//        加载驱动
    Class.forName("com.mysql.jdbc.Driver");
//填写url,用户名,密码获得链接
    Connection connection= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bookmug?useUnicode=true&characterEncoding=utf-8" + 
            "","root","root123");
    System.out.println(connection);
    
//
    String sql="insert into book_table(book_name,book_author) values(?,?)";
    PreparedStatement statement = (PreparedStatement) connection.prepareCall(sql);
    statement.setString(1,"三国");
    statement.setString(2,"胖三");
    statement.executeUpdate();
//
    String sql1="delete from book_table where book_id=?";
    PreparedStatement statement1 = (PreparedStatement) connection.prepareCall(sql1);

    statement.setInt(1,2);
    statement.executeUpdate();
//
    String sql2="update book_table set book_name=? where book_id=?";
    PreparedStatement statement2 = (PreparedStatement) connection.prepareCall(sql2);
    statement.setString(1,"大大大");
    statement.setInt(2,3);
    statement.executeUpdate();
    
    
}
}

 

posted @ 2021-07-16 19:55  十万万万个为什么  阅读(76)  评论(0)    收藏  举报