java程序连接MySQL数据库

驱动程序:mysql-connector-java-5.1.7-bin.jar

程序示例如下:

package commonProject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JavaForJdbc {

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        String dbDriver = "com.mysql.jdbc.Driver";//声明mysql驱动
        String url = "jdbc:mysql://139.129.34.134:3306/database01";//声明数据源
        Connection conn = null;//声明与数据库的连接
        Statement stmt = null;//声明执行SQL语句
        ResultSet rs = null;//声明结果集
        
        
        Class.forName(dbDriver);//加载数据库驱动,一般可不执行,执行该句可以提前检查jdbc驱动是否存在。
        conn = DriverManager.getConnection(url,"username","password");//连接数据库
        stmt = conn.createStatement();//创建 Statement对象
        rs = stmt.executeQuery("SELECT * FROM userTable");执行查询语句
        while(rs.next()){
            System.out.println("id:"+rs.getString(1)+" name:"+rs.getString(2)+" age:"+rs.getString(3));
        }
    }

}

 

posted @ 2016-11-14 13:54  且听风吟-wuchao  阅读(272)  评论(0编辑  收藏  举报