javaweb之eclipse工程连接mysql数据库
准备工作:
1.在mysql官网下载mysqlconnection的jar包
输入网址:mysql.com—点击DOWNLOADS——下拉选择MySQL Community (GPL) Downloads »——选择Connector/J——下载后解压——找到mysql-connector-java-8.0.22.jar
2.将mysql-connector-java-8.0.22.jar复制到当前javaweb工程
3.构建路径:右击当前项目——选择Build Path——Configure Build Path——Libraries——AddJARs——将之前复制在lib文件下的mysql-connection导入——Apply and Close
看到如下则成功:
4.在src中创建com.mysqlconnection包和mysqlconnection类
进行连接
public class mysqlconnect {
public static void main(String[] args) {
//判断驱动是否加载成功
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //固定语法
System.out.print("成功加载驱动!");//提示语
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.print("加载驱动失败!");
e.printStackTrace();
}
//连接mysql
Connection con;
//localhost为主机名 3306为mysql的端口号 web:进行连接的目标数据库
String url = "jdbc:mysql://localhost:3306/web?serverTimezone=UTC";
//登录数据库用户名
String user = "root";
//登录数据库的密码
String password = "password";
try {
con = DriverManager.getConnection(url,user,password); //将参数传给驱动进行连接
if(!con.isClosed()) {
System.out.print("成功连接数据库!");
//创建statement对象
Statement statement = con.createStatement();
//声明一个sql语句查询student表中所有信息
String sql = "select * from student";
ResultSet rs = statement.executeQuery(sql);
//循环输出打印student表中的id name age
while (rs.next()){System.out.print(rs.getString("id"));
System.out.print("");
System.out.print(rs.getString("name"));
System.out.print("");
System.out.print(rs.getString("age"));
System.out.print("\t");}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
标签:javaweb,rs,eclipse,System,String,mysql,print,out
来源: https://www.cnblogs.com/clinch/p/14229130.html