51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

Java学习之路-SQL-添加与修改记录

使用PreparedStatement对象完成记录的添加和修改。
SQL/Demo.java


package cn.antraces.SQL;

import java.sql.*;

public class Demo {

/**
 * 查询
 * @param statement
 * @throws SQLException
 */
public static void select (Statement statement) throws SQLException {
    ResultSet resultSet = statement.executeQuery("select * from course");
    while (resultSet.next()) {
        System.out.print(resultSet.getString("cno"));
        System.out.println("\t" + resultSet.getString("cname"));
    }
}

/**
 * 增加
 * @param connection
 * @param statement
 * @return
 * @throws SQLException
 */
public static int insert (Connection connection, Statement statement) throws SQLException {
    PreparedStatement preparedStatement = connection.prepareStatement("insert into course value(?, ?)");
    preparedStatement.setString(1, "a0");
    preparedStatement.setString(2, "我丢");
    return preparedStatement.executeUpdate();
}

/**
 * 修改
 * @param connection
 * @param statement
 * @return
 * @throws SQLException
 */
public static int update (Connection connection, Statement statement) throws SQLException {
    PreparedStatement preparedStatement = connection.prepareStatement("update course set cno=? where cname=?");
    preparedStatement.setString(1, "a00 ");
    preparedStatement.setString(2, "我丢");
    return preparedStatement.executeUpdate();
}

public static void main (String[] args) throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.cj.jdbc.Driver");
    Connection connection = DriverManager.getConnection(
            "jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT", "root", "wodiu");
    //System.out.println(connection);
    Statement statement = connection.createStatement();
    select(statement);
    System.out.println("\ninsert : " + insert(connection, statement));
    select(statement);
    System.out.println("\nupdate : " + update(connection, statement));
    select(statement);
}

}


赞(2)
未经允许不得转载:工具盒子 » Java学习之路-SQL-添加与修改记录