Java 写 my sql 常用格式:

添加数据:
Class.forName(“com.mysql.jdbc.Driver”);
Connection connection= DriverManager.getConnection(“jdbc:mysql://localhost:3306/testbook”,“root(数据库账号)”,“123(数据库密码)”);

    PreparedStatement preparedStatement = connection.prepareStatement("insert into ueset(name,password,type)values (?,?,?)");
    preparedStatement.setString(1,"xiaoming"); (类型)(位置,数据)
    preparedStatement.setString(2,"123"); (类型)(位置,数据)
    preparedStatement.setString(3,"男"); (类型)(位置,数据)
    preparedStatement.executeUpdate(); (类型)(位置,数据)
    execueUpdate() 

删除数据:
Class.forName(“com.mysql.jdbc.Driver”);
Connection connection= DriverManager.getConnection(“jdbc:mysql://localhost:3306/testbook”,“root”,“123”);

    PreparedStatement preparedStatement = connection.prepareStatement("delete from ueset where id=?");
    preparedStatement.setInt(1,1); (类型)(位置,数据)
    preparedStatement.executeUpdate();

修改数据:
Class.forName(“com.mysql.jdbc.Driver”);
Connection connection= DriverManager.getConnection(“jdbc:mysql://localhost:3306/testbook”,“root”,“123”);

    PreparedStatement preparedStatement = connection.prepareStatement("update ueset set name=? where id=?");
    preparedStatement.setString(1,"战绩顺城大街"); (类型)(位置,数据)
    preparedStatement.setInt(2,4); (类型)(位置,数据)
    preparedStatement.executeUpdate();

查询所有:
Class.forName(“com.mysql.jdbc.Driver”);
Connection connection= DriverManager.getConnection(“jdbc:mysql://localhost:3306/testbook”,“root”,“123”);

    PreparedStatement preparedStatement = connection.prepareStatement("select * from ueset");
    ResultSet resultSet = preparedStatement.executeQuery(); (executeQuery用于查询)
         while (resultSet.next()){  resultSet.next()有就返回true 没有就返回false)
         (遍历数据库将值给遍历出来)
         (查询数据是什么类型就get什么类型,名字为所需要查询的类型名)
        String name = resultSet.getString("name");       
        String passwprd = resultSet.getString("password");
        String type = resultSet.getString("type");
        System.out.println(name+passwprd+type);  (打印)

带条件查询

Class.forName(“com.mysql.jdbc.Driver”);
Connection connection= DriverManager.getConnection(“jdbc:mysql://localhost:3306/testbook”,“root”,“123”);

    PreparedStatement preparedStatement = connection.prepareStatement("select * from ueset where id=?");
    preparedStatement.setInt(1,6);
    ResultSet resultSet = preparedStatement.executeQuery();
    while (resultSet.next()){
        String name = resultSet.getString("name");
        String passwprd = resultSet.getString("password");
        String type = resultSet.getString("type");
        System.out.println(name+passwprd+type);
    }
    原理和上一样,只不过加了一个条件。

你可能感兴趣的:(学习总结,my,sql)