首页 > 代码库 > mysql 入门 jdbc

mysql 入门 jdbc

402c8590_c1a1_0131_ac3a_001e90766fd0

在java程序中连接mysql,先要到mysql的网站上面去下载驱动,并且安装,默认安装在c盘(我的都是默认安装,目录为C:\Program Files\MySQL\MySQL Connector J),如果mysql也是默认安装的话,刚安装的路径在mysql目录下面,地址为http://www.mysql.com/products/connector/,如果是java,则下载JDBC Driver for MySQL (Connector/J)

下载完成安装完成后,在开发工具里引入安装好后目录下的mysql-connector-java-5.1.30-bin.jar,引入后代码如下:

package com.jll.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

public class Driver {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        List list = new LinkedList();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?" +
                    "user=root&password=root");
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT * FROM article");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
       
        try {
            while(rs.next()){
                int i = rs.getInt("id");
                list.add(i);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            try {
                rs.close();
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
       
        for(int i = 0;i<list.size();i++){
            System.out.println(list.get(i));
        }
    }
   
   

}