当前位置:   article > 正文

eclipse连接mysql数据库_eclipse连接数据库

eclipse连接数据库

#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("**************");
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

}

在这里插入图片描述

##4.把执行sql语句下方【多行注释】的符号去掉 /**/ ,则查询的是goods表中的id字段和type字段
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/685368
推荐阅读
相关标签
  

闽ICP备14008679号