jdbc for mysql demo

来源:互联网 发布:手扶电梯内部 知乎 编辑:程序博客网 时间:2024/05/16 08:59
http://www.cnblogs.com/zfc2201/archive/2011/08/24/2152685.htmlpackage com.huawei.mysql; import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException; public class MySqlTest {    public static void main(String[] args) throws SQLException {        Connection conn = null;        PreparedStatement stmt = null;        ResultSet rs = null;         try {            Class.forName("com.mysql.jdbc.Driver");            conn = DriverManager.getConnection(                    "jdbc:mysql://localhost:3306/test", "root",                    "123");            stmt = conn.prepareStatement("select * from person where id=?");            stmt.setInt(1, 10);            rs = stmt.executeQuery();            while (rs.next()) {                System.out.println(rs.getInt("id"));                System.out.println(rs.getString("name"));                System.out.println("----------------------------");            }        } catch (ClassNotFoundException e) {            e.printStackTrace();        } catch (SQLException e) {            e.printStackTrace();        } finally {            if (rs != null)                rs.close();            if (stmt != null)                stmt.close();            if (conn != null)                conn.close();        }    }}


原创粉丝点击