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

mysql连接jdbc查询代码

时间:2016-02-25 15:09:58      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

package com.simope.test;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class ConnToMySql {

    public static final String url = "jdbc:mysql://localhost/my_db";
    
    public static final String userName = "root";
    
    public static final String password = "root";
    
    public static void main(String[] args) {
        
        Connection conn = null;
        
        Statement stmt = null;
        
        ResultSet rs = null;
        
        try {
            Class.forName("com.mysql.jdbc.Driver");
            
            conn = (Connection) DriverManager.getConnection(url, userName, password);
            
            stmt = (Statement) conn.createStatement();
            
            String sql = "select * from sys_user";
            
            rs = stmt.executeQuery(sql);
            
            while (rs.next()) {
                System.out.println("按照列下标:" + rs.getInt(1));
                System.out.println("按照列名:" + rs.getInt("userID"));
            }
            
        } catch (Exception e) {
            System.out.println("first:" + e);
        } finally {
            try {
                rs.close();
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                System.out.println("second:" + e);
            }
        }
        
    }
}

所用到的jar包:mysql-connector-java-5.1.5-bin.jar

mysql连接jdbc查询代码

标签:

原文地址:http://www.cnblogs.com/JimLy-BUG/p/5216929.html

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