JDBC链接MySQL的一个相对完美的小程序

来源:互联网 发布:微信授权登陆api java 编辑:程序博客网 时间:2024/05/08 01:24

import java.sql.*;

public class TestJDBC {

public static void main(String[] args)  {    ResultSet re = null;    Statement st = null;    Connection conn = null;    try {        Class.forName("org.gjt.mm.mysql.Driver");//实例化自动向DriverManager注册        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Newdata","root","45628852");        System.out.println("Success connect Mysql server!");         st = conn.createStatement();         re = st.executeQuery("select * from students");        while(re.next()) {            System.out.println(re.getString("name")+" "+re.getInt("age")+" "+re.getString("sports"));        }//遍历    } catch(ClassNotFoundException ex) {            ex.printStackTrace();    } catch (SQLException e) {        System.out.println("get a error");        e.printStackTrace();    } finally {        try {            if(re!=null)                re.close();                re = null;            if(st!=null)                st.close();                st = null;            if(conn!=null)                conn.close();                conn = null;        } catch(SQLException ex) {            ex.printStackTrace();        }    }}

}

0 0