1. 添加依赖(因为创建的是maven项目 所以不用去创建lib目录去导入包了 方便)
点击查看代码
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
点击查看代码
import java.sql.*;
public class jdbc_web {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url="jdbc:mysql://127.0.0.1:3306/user?serverTimezone=UTC&&useSSL=false";
String username="root";
String password="root";
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from student");
while(resultSet.next()){
System.out.println("name:"+resultSet.getObject("name"));
System.out.println("age:"+resultSet.getObject("age"));
System.out.println("address:"+resultSet.getObject("address"));
System.out.println("brithday:"+resultSet.getObject("brithday"));
}
resultSet.close();
statement.close();
connection.close();
}
}
点击查看代码
public class jdbc01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url="jdbc:mysql://127.0.0.1:3306/user?serverTimezone=UTC&&useSSL=false";
String username="root";
String password="root";
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
String sql="INSERT INTO student (name,age,address,brithday)values(?,?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,"小王");
preparedStatement.setInt(2,14);
preparedStatement.setString(3,"上海");
preparedStatement.setDate(4, new java.sql.Date(System.currentTimeMillis()));
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("加入成功");
}else {
System.out.println("加入失败");
}
preparedStatement.close();
connection.close();
}
}