欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java jdbc 入门示例删除行,javajdbc,package cn.o

来源: javaer 分享于  点击 26218 次 点评:163

java jdbc 入门示例删除行,javajdbc,package cn.o


package cn.outofmemory.snippets.core;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Statement;public class DeleteExample {  public static void main(String[] args) {    Connection connection = null;    try {        // Load the MySQL JDBC driver        String driverName = "com.mysql.jdbc.Driver";        Class.forName(driverName);        // Create a connection to the database        String serverName = "localhost";        String schema = "test";        String url = "jdbc:mysql://" + serverName +  "/" + schema;        String username = "username";        String password = "password";        connection = DriverManager.getConnection(url, username, password);        System.out.println("Successfully Connected to the database!");    } catch (ClassNotFoundException e) {        System.out.println("Could not find the database driver " + e.getMessage());    } catch (SQLException e) {        System.out.println("Could not connect to the database " + e.getMessage());    }    try {      /*        * For deletes that are not executed frequently we should use the statement API.       * deleteCount contains the number of deleted rows       */      Statement statement = connection.createStatement();      int deleteCount = statement.executeUpdate("DELETE FROM test_table WHERE test_col='test_value_1'");      System.out.println("Deleted test_value_1 row successfully : " + deleteCount);      /*        * For deletes that are executed frequently we should        * use the prepared statement API.       * deleteCount contains the number of deleted rows       */      PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM test_table WHERE test_col=?");      preparedStatement.setString(1, "test_value_2");      deleteCount = preparedStatement.executeUpdate();      System.out.println("Deleted test_value_2 row successfully : " + deleteCount);    } catch (SQLException e) {       System.out.println("Could not execute statement " + e.getMessage());    }  }}

输出

Successfully Connected to the database!Deleted test_value_1 row successfully : 1Deleted test_value_2 row successfully : 1
相关栏目:

用户点评