public class ConnectionDataBaseTest {
public static final String driver="com.mysql.jdbc.Driver";//驱动
public static final String url="jdbc:mysql://localhost:3306/ssm";//指向数据库名
public static final String user="root";//用户
public static final String password="root";//密码
public static void main(String[]args){
try {
Class.forName(driver);//加载驱动
Connection connection=DriverManager.getConnection(url,user,password);//创建连接
queryDataBase(connection);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e){
e.printStackTrace();
}
}
//查询数据
public static void queryDataBase(Connection connection){
try {
String sql="SELECT * FROM user";
Statement statement=connection.createStatement();
ResultSet resultSet=statement.executeQuery(sql);
int id;
String name=null;
int age;
String gender=null;
while (resultSet.next()){
id=resultSet.getInt("id");
name=resultSet.getString("name");
age=resultSet.getInt("age");
gender=resultSet.getString("gender");
System.out.println("id:"+id+";name:"+name+";age:"+age+";gender:"+gender);
}
statement.close();
resultSet.close();
} catch (SQLException e){
e.printStackTrace();
}finally {
System.out.println("数据查询成功!");
}
}
//插入数据
public static void insertDataBase(Connection connection){
try {
PreparedStatement preparedStatement=
connection.prepareStatement("INSERT INTO user(id,name,age,gender) VALUES (?,?,?,?)");
preparedStatement.setInt(1,4);
preparedStatement.setString(2,"马云");
preparedStatement.setInt(3,30);
preparedStatement.setString(4,"男");
preparedStatement.executeUpdate();//插入,修改和删除数据时都要用excuteUpdate()
preparedStatement.close();
} catch (SQLException e){
e.printStackTrace();
}
}
//修改数据
public static void updateDataBase(Connection connection){
try {
PreparedStatement preparedStatement=connection.prepareStatement("UPDATE user SET name=? WHERE id=?");
preparedStatement.setString(1,"马化腾");
preparedStatement.setInt(2,3);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//删除数据
public static void deleteDataBase(Connection connection){
try {
PreparedStatement preparedStatement=connection.prepareStatement("DELETE FROM user WHERE id=?");
preparedStatement.setInt(1,2);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}