码迷,mamicode.com
首页 > 数据库 > 详细

java与mysql连接

时间:2015-10-25 19:19:09      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

package DBHelper;
 
import java.sql.*;
 
public class Demo {
    public static void main(String[] args) {
        String driver = "com.mysql.jdbc.Driver";
        String dbName = "test";
        String passwrod = "root";
        String userName = "root";
        String url = "jdbc:mysql://localhost:3306/" + dbName;
        String sql = "select * from test";
 
        try {
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url, userName,
                    passwrod);
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                System.out.println("id : " + rs.getInt(1) + " name : "
                        + rs.getString(2) );
            }
 
            // 关闭记录集
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
 
            // 关闭声明
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
 
            // 关闭链接对象
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}

 

java与mysql连接

标签:

原文地址:http://www.cnblogs.com/xiaobo-Linux/p/4909192.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!