IntelliJ IDEA中JAVA连接MYSQL

  1. 云栖社区>
  2. 博客>
  3. 正文

IntelliJ IDEA中JAVA连接MYSQL

桃子红了呐 2017-08-27 15:07:00 浏览1327
展开阅读全文

1.下载mysql包

422101-20161019010030248-1241644113.png

422101-20161019010038295-1432367576.png

2.项目中引入mysql包

422101-20161019010137263-1922680175.png

422101-20161019010143701-1525409881.png

422101-20161019010151623-1049434845.png

3.连接数据库,查询结果

422101-20161019010217310-1727146793.png

422101-20161019010222185-386123755.png

看jdbc数据库连接类

package Facade;
import java.sql.*;
/**
 * Created by Jiqing on 2016/10/18.
 */
public class JDBCFacade {

    private Connection conn=null;
    private Statement statement=null;

    public void open(String driver,String jdbcUrl,String userName,String userPwd) {
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(jdbcUrl,userName,userPwd);
            statement = conn.createStatement();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int executeUpdate(String sql) {
        try {
            return statement.executeUpdate(sql);
        }
        catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    public ResultSet executeQuery(String sql) {
        try {
            return statement.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void close() {
        try {
            conn.close();
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

客户端执行

package Facade;
import java.sql.ResultSet;

/**
 * Created by Jiqing on 2016/10/18.
 */
public class Client {
    public static void main(String args[])
    {
        try {
            JDBCFacade jdbc= new JDBCFacade();
            jdbc.open("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/tpshop","root","123456");
            ResultSet rs =  jdbc.executeQuery("select * from tp_admin");

            while(rs.next()){
                String email = rs.getString("email") ;
                System.out.println(email);

            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }


    }
}




本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/5975771.html,如需转载请自行联系原作者

网友评论

登录后评论
0/500
评论
桃子红了呐
+ 关注