java链接数据库,增删改查用法
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class Text {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
/*
* 配置四大驱动,用于获得链接
* 用户名 密码
* url
* 驱动
*/
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//填写url 用户名,密码获得链接
Connection connection =(Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bookmeg?useUnicode=true&characterEncoding=utf-8", "root", "root123");
System.out.println(connection);
/*
* 插入
* 构造sql语句
* 获得执行sql的对象(根据connection获得的)
*往sql里赋值
* 执行
*/
//插入
// String sql ="insert into book_table(book_name,book_author,book_price)"+"values(?,?,?)";
// PreparedStatement statement =(PreparedStatement) connection.prepareStatement(sql);
// statement.setString(1, "三国");
// statement.setString(2, "王龙");
// statement.setInt(3, 500);
// int result =statement.executeUpdate();
// System.out.println(result);
//删除
String sql="delete from book_table where book_id=?";
PreparedStatement statement =(PreparedStatement) connection.prepareStatement(sql);
statement.setInt(1,7);
int result =statement.executeUpdate();
System.out.println(result);
//修改
// String sql = "update book_table set book_author=? where book_name=?";
// PreparedStatement statement =(PreparedStatement) connection.prepareStatement(sql);
// statement.setString(1, "罗贯中");
// statement.setString(2, "三国");
// int result =statement.executeUpdate();
// System.out.println(result);
// }
//查询
String sql="select * from users_table ";
PreparedStatement statement=(PreparedStatement) connection.prepareStatement(sql);
ResultSet set=statement.executeQuery();
}}

浙公网安备 33010602011771号