1.创建java项目并导入jar包
mysql-connector-java-5.1.9-bin.jar
链接:https://pan.baidu.com/s/1p-e9U2WUr4cPglXpoILOxA
提取码:g829
2.建立 test 数据库并创建表 student
student表定义如下
3.编写实现代码
public class SqlCon {
private static final String DRIVER = "com.mysql.jdbc.Driver"; //驱动程序名
private static final String URL = "jdbc:mysql://localhost:3306/test"; //数据库的路径
private static final String USER = "root"; //用户名
private static final String PASSWORD = "123456"; //密码
Connection connection=null;
Statement statement=null;
ResultSet rs=null;
//在构造方法中为conn对象实例化,取得数据库的连接对象
public SqlCon() throws SQLException, ClassNotFoundException {
try {
Class.forName(DRIVER); //加载驱动程序
connection = DriverManager.getConnection(URL, USER, PASSWORD); //连接数据库
statement=connection.createStatement();
}catch (Exception e){
e.printStackTrace();
}
}
//查
public void query(String tableName) throws SQLException {
String sql = "select * from "+tableName; // 要执行的SQL语句
ResultSet rs = statement.executeQuery(sql);// ResultSet类,用来存放获取的结果集
int sid = 0;
String sname = null;
while (rs.next()) {
sid = rs.getInt("sid");// 获取id这列数据
sname = rs.getString("sname");// 获取id这列数据
System.out.println(sid + ":" + sname);// 输出
}
}
//增
public void insert(String tableName,int sid,String sname) throws SQLException {
String sql = "insert into "+tableName+" values("+sid+",'"+sname+"');";
statement.executeUpdate(sql);
}
//删
public void delete(String tableName,int sid) throws SQLException {
String sql = "delete from "+tableName+" where sid="+sid;
statement.executeUpdate(sql);
}
//改
public void update(String tableName,int sid,String sname) throws SQLException {
String sql = "update student set sname='"+sname+"' where sid="+sid;
statement.executeUpdate(sql);
}
//关闭数据库
public void close() {
if (connection != null) { //表示现在有连接对象
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws SQLException, ClassNotFoundException {
SqlCon sqlCon=new SqlCon();
// sqlCon.insert("student",9,"cz");
// sqlCon.delete("student",6);
// sqlCon.update("student",5,"cd");
sqlCon.query("student");
// sqlCon.close();
}
}
4.运行截图