public void fun1() throws ClassNotFoundException, SQLException {
/*
* jdbc四大配置参数
* driverClassName:com.mysql.jdbc.Driver
* url:jdbc:mysql://localhost:3306/test
* username:root
* password:123 *
*/
Class.forName("com.mysql.jdbc.Driver");//加载驱动类
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "root";
//使用url username password 得到链接对象
Connection con = (Connection) DriverManager.getConnection(url,username,password);
System.out.println(con);
}
增加记录
/*1,通过Connection 对角创建Statement
* Statement语句发送器,它的功能就是向数据发送sql语句
* 调用它的int executeUpdate(String sql),它可以发送,dml,ddl *
*/
Statement stmt = con.createStatement(); // con是链接对象
String sql = "INSERT INTO users VALUES(null,'小明',123456,'88')";// 插入中文,请将数库修改为 utf8_unicode_ci , 当 主键设置为自增ID时,插入时,主键写 null 值,即可自增 如上
int m = stmt.executeUpdate(sql);
System.out.println(m);
删除记录
String sql = "delete from users where age between 16 and 20"; //删除 年龄在16到20之间的的记录,包括 16和20在内
String sql = "delete from users where age = 20"; // 删除,年龄为20的记录
修改记录 (全部修改,两件条件修改,一个条件修改)
Statement stmt = con.createStatement();
//where条件修改条件所指的记录
String sql = "update users set username='鹿晗', password='love19880818' where userid='2'";//修改同时满足两个条件的记录 where userid=2 or username="鹿晗"的记录 修改为年龄为18
String sql = "update users set age='18', password='love19880818' where userid='2' or username='鹿晗'";
//把10到30之间年龄的字段,年龄修改为 20 , between and ,区间判断
String sql = "update users set age=20 where age between 10 and 30";
//不加where条件,修改此字段的全部记录
String sql = "update users set username='鹿晗', password='love19880818'";
String sql = "update users set age=20 where username in<'zhangsan','luhan'>";
//必须用is ,不能用 = ,当记录里有null的值时,返回 true
String sql = "update users set age=20 where age is null";
int m = stmt.executeUpdate(sql);
System.out.println(m);
查询记录
/*
* jdbc四大配置参数
* driverClassName:com.mysql.jdbc.Driver
* url:jdbc:mysql://localhost:3306/test
* username:root
* password:123 *
*/
Class.forName("com.mysql.jdbc.Driver"); //加载驱动类
String url = "jdbc:mysql://localhost:3306/blog";
Connection con = DriverManager.getConnection(url,"root","root");
Statement stmt = con.createStatement();
String sql = "select * from users";
ResultSet re = stmt.executeQuery(sql); //查询方法
while(re.next()) { // resultset 的 next 方法,可以把行光标向下移一行
int userid = re.getInt("userid"); // 读取字段为int类型的数据
String username = re.getString("username"); //读取字段为String 类型的数据
int age = re.getInt("age");
System.out.println(userid+" | "+username+" | "+age );
}//关闭资源
re.close();
stmt.close();
con.close();