Java教程

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

本文主要是介绍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();
    
    
}
}

 

这篇关于java链接数据库,增删改查用法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!