数据库相关操作:
1.创建数据库studentdb要求如下:
(1)安装mysql(字符集设置为utf-8)和navicate;
(2)在mysql里创建数据库studentdb,字符集编码UTF-8;
(3)新建表user,字段要求如下:
id (自增) 整型 长度10
name 字符型 长度 50
password 字符型 长度 50
(4)向user表手工插入两天记录
1 张三 123456
2 李四 123abcd
2.定义一个TestJDBC类要求如下:
(1)添加mysql数据库驱动包
(2)建立数据库的连接
(3)利用statement语句向表中插入一条记录
“王五”,“abcdef123”
(4)利用statement语句删除表中记录id为2的数据
(5)关闭结果集,关闭Statement语句,关闭连接
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestJDBC {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// TODO Auto-generated method stub
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/studentdb?user=root&password=310333&useUnicode=true&characterEncoding=UTF8";
Connection connection=DriverManager.getConnection(url);
Statement statement=connection.createStatement();
ResultSet rs=statement.executeQuery("SELECT*FROM user");
statement.execute("insert into user(name.password))values('王五','1234abcd')");
statement.executeLargeUpdate("delect from user where id=2");
while(rs.next()){
int id=rs.getInt(1);
String name=rs.getString(2);
String password=rs.getString("password");
System.out.println("id"+id+"name"+name+"password"+password);
}
}
1.创建数据库studentdb要求如下:
(1)在mysql里创建数据库studentdb,字符集编码UTF-8;
(2)右击studentdb,选择执行studentdb.sql文件,自动生成users表
2.定义一个TestJDBC类要求如下:
(1)建立一个静态方法getConnection(),功能实现可以获取一个studentdb数据库连接;
(2)在main方法里,利用statement语句向表中插入一条记录
“王五”,“abcdef123”
(3)利用statement语句删除表中记录id为2的数据
(4)利用PreparedStatement语句向表users插入一条记录
小小 abc123
(5)利用PreparedStatement语句更新表中的记录id=3的记录的密码为 “ahtcm123”
(6)关闭结果集,关闭Statement语句,关闭连接
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
public class TestJDBC {
public static Connection getConnection() {
Connection con=null;
String url="jdbc:mysql://localhost:3306/studentdb?user=root&password=tan123&useUnicode=true&characterEncoding=UTF8";
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(url);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return con;
}
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
Connection con=null;
Statement st= null;
con=TestJDBC.getConnection();
st=con.createStatement();
st.execute("insert into users(name,password) values('王五','abcdef123')");
st.execute("delete from users where id=2");
PreparedStatement ps1=con.prepareStatement("insert into users(name,password)value(?,?)");
ps1.setString(1, "小小");
ps1.setString(2, "abc123");
ps1.execute();
PreparedStatement ps2=con.prepareStatement("update users set password='ahtcm123' where id=3");
ps2.execute();
st.close();
ps1.close();
ps2.close();
con.close();
}
}