Java基础代码库:JDBC连接MySQL

import java.sql.*;
public class mysql
{
    public static void main(String[] args)
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/test";
            String userName = "root";
            String passwd = "root";
            Connection con = DriverManager.getConnection(url, userName, passwd);
            Statement st = con.createStatement();
            String query = "select * from user;";
            ResultSet rs = st.executeQuery(query);
            while(rs.next())
            {
                int num = rs.getInt("id");
                String name = rs.getString("username");
                System.out.println(num+" "+name);
            }
            rs.close();
            st.close();
            con.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}
posted @ 2012-08-13 20:41  苏堤白堤杨公堤  阅读(237)  评论(0编辑  收藏  举报