一.JDBC连接数据库
package com.vetor;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC {
public static void main(String[] args) {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3307/student";
String username = "root";
String password = "root";
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
String sql = "update student set age=20 where age=18";
int n = stmt.executeUpdate(sql);
System.out.println("更新影响的行数是: " +n);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
二. 测试结果
三. 测试错误类型
3.1端口错误
3.2数据库名称错误
3.3导入驱动错误/驱动名称写错
|