咱们废话不多说,直接进入正题吧,要想连接数据库,首先得下载一个驱动,下面是下载链接
链接:https://pan.baidu.com/s/1gRj8n9sCP-aDQsJjHyCAow
提取码:z9rj
要下载其他版本的驱动可以去官网下载 https://dev.mysql.com/downloads/connector/j/
驱动下载之后呢,在想要使用数据库的项目的下方新建一个lib目录,把驱动复制到这个目录下面
如下图所示:
然后鼠标右键点击此项目,选择buildpath-->configure build path-->libraries-->Add JRs..,然后选择lib目录下的驱动,点击确定就OK啦,这个时候Referenced Libraries里面就有刚才的驱动啦
准备工作做好之后呢,就可以写程序啦,代码如下:
import java.sql.*;
public class Test {
//JDBC驱动名称及数据库URL
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost:3306/student";
//数据库的用户名与密码
static final String USER="root";
static final String PASS="ly1314520";
public static void main(String args[]){
Connection conn=null;
Statement stmt=null;
try{
Class.forName("com.mysql.jdbc.Driver");//注册JDBC驱动
//打开连接
System.out.println("连接数据库。。。");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("实例化Statement对象....");
stmt=conn.createStatement();
String sql;
sql="SELECT id,name,url FROM website";
ResultSet rs=stmt.executeQuery(sql);
//展开结果集数据库
while(rs.next()){
int id=rs.getInt("id");
String name =rs.getString("name");
String url=rs.getString("url");
//输出数据
System.out.print("ID: "+id);
System.out.print(",站点名称:"+name);
System.out.print(",站点URL: "+url);
System.out.print("\n");
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();//处理错误
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Good Bye");
}
}
好啦,这次就到这里啦