赞
踩
#eclipse连接数据库
以MySQL8.0为例:
##1.eclipse连接MySQL的前提是:安装mysql8.0→配置好mysql的环境变量→创建数据库→连接数据库→创建表结构→添加数据→查询数据
##2.引用我们需要的jar包
##3.创建BaseDao.java文件
package view;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//以上导入部分也可以写为 import java.sql.*;
public class BaseDao {
//**注册驱动** protected static final String driver="com.mysql.cj.jdbc.Driver"; //**获取连接** protected static final String url="jdbc:mysql://localhost:3306/db_shop"; //db_shop是数据库名 protected static final String dbUser="root"; protected static final String dbPwd=""; //没设置密码,所以为空 public static Connection conn=null; public static Connection getConnection() { try { if(conn==null) { Class.forName(driver); System.out.println("数据驱动加载成功"); conn=DriverManager.getConnection(url,dbUser,dbPwd); System.out.println("数据库连接成功"); //执行sql /*String sql="select * from goods"; PreparedStatement ps =conn.prepareStatement(sql); ResultSet rs=ps.executeQuery(); //处理查询结果集 while(rs.next()) { int id=rs.getInt("id"); String type=rs.getString("type"); System.out.println(id+"-"+type+"-"); }*/ } }catch(Exception e) { e.printStackTrace(); } return conn; } public static void main(String[] args){ System.out.println("**************"); BaseDao basedao=new BaseDao(); basedao.getConnection(); System.out.println("**************"); }
}
##4.把执行sql语句下方【多行注释】的符号去掉 /**/ ,则查询的是goods表中的id字段和type字段
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。