mysql驱动下载见最后
步骤
1. 在项目中新建libs包
2. 赋值jar包到libs中(mysql-connector-java-5.1.37-bin.jar)
3. jar包加入项目
4. 注册驱动
Class.forName("com.mysql.jdbc.Driver");
5. 获取数据库连接对象
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "root.123");
6. 定义sql语句
String sql="select * from emp";
7. 获得执行sql的对象
Statement statement = connection.createStatement();
8. 执行sql
boolean execute = statement.execute(sql);
9. 处理结果
System.out.println(execute);
10. 释放资源
statement.close();
connection.close();
遇到的问题
1. Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
Caused by: java.lang.NullPointerException
解决:驱动包用错,重新下载mac版mysql驱动包
- mysql驱动下载流程:
https://dev.mysql.com/downloads/connector/j/
- 替换之前的mysql驱动
最后再重新添加新的驱动jar包
例子
public void funTest01() {
// Class.forName("com.mysql.jdbc.Driver");//mysql5版本之后可以删除
Connection connection = null;
Statement statement = null;
try {
connection = DriverManager.getConnection("jdbc:mysql:///student",
"root", "root.123");//省略localhost:3306
String sql = "update stu set math=90 where id=2";
statement = connection.createStatement();
int count = statement.executeUpdate(sql);
if(count>0){
System.out.println("操作成功");
}else {
System.out.println("操作失败");
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}