`

java连接mysql实例

阅读更多
/**
* @(#)JDBCTest.java
*
*
* @author keer2345
* @version 1.00 2008/8/11
*/

import java.sql.*;

public class JDBCTest {

    public static void main(String[] args) {
        // 1. 注册驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch(ClassNotFoundException ex) {
            ex.printStackTrace();
        }
       
        // 声明变量,使用,而后关闭
        Connection conn = null;        //数据库连接
        Statement stmt = null;         //数据库表达式
        ResultSet rs = null;             //结果集
       
        try {
            //2. 获取数据库的连接
            conn = DriverManager.getConnection
                ("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=GBK","root","");
           
            //3. 获取表达式
            stmt = conn.createStatement();
           
                // 插入数据
            stmt.executeUpdate("insert into Student (username, password, age) values ('张三','1234',20)");
           
            //4. 执行SQL
            rs = stmt.executeQuery("select * from Student");
           
            //5. 现实结果集里面的数据
            while(rs.next()) {
                System.out.println("编号=" + rs.getInt(1));
                System.out.println("姓名=" + rs.getString("username"));
                System.out.println("密码=" + rs.getString("password"));
                System.out.println("年龄=" + rs.getString("age"));
                System.out.println("---------------");
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        finally {
            try {
                if(rs != null) {
                    rs.close();
                }
                if(sm != null) {
                    sm.close();
                }
                if(conn != null) {
                    conn.close();
                }
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics