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

 

上一篇:关于 junit4 90% 的人都不知道的特性,详解 junitperf 的实现原理


下一篇:JAVA 中级 / JDBC / JDBC系列教材 (五)- 在JDBC中使用预编译STATEMENT 以及它的优点