IDEA+JDBC+MAVEN
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//1.导入驱动jar包 mysql-connector-java-5.1.37-bin.jar
//maven中配置
/*
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>*/
//2. 注册驱动
Class.forName("com.mysql.jdbc.Driver");
//3. 获取数据库连接对象 Connection
connection = DriverManager.
getConnection("jdbc:mysql://localhost:3306/eesy_mybatis","root","root");
//4. 定义sql
String sql = "select * from user where id = ?";
//5. 获取执行sql语句的对象 Statement
preparedStatement = connection.prepareStatement(sql);
//6. 设置参数,第一个参数为 sql 语句中参数的序号(从 1 开始),第二个参数为设置的参数值
preparedStatement.setInt(1,46);
//7. 执行sql,接受返回结果
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet);
System.out.println(resultSet.getString("username"));
}
resultSet.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
执行的时候出现 java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
找不到驱动
原因:jar包未加载成功 配置maven是 未自动加载jar包
解决方法:右键项目 maven->reimport