查询表里的数据
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
public class test1 {
public static void main(String[] args) throws Exception{
Properties info = new Properties();
info.load(new FileInputStream("src\\jdbc.properties"));
String user = info.getProperty("user");
String password = info.getProperty("password");
String driver = info.getProperty("driver");
String url = info.getProperty("url");
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取链接
Connection connection = DriverManager.getConnection(url,user,password);
// 执行语句
String sql ="select id,age,name from user";
Statement statement = connection.createStatement();
// 执行增删改语句,int update = statement.executeUpdate(sql);
// 执行查询语句,返回一个结果集
ResultSet set = statement.executeQuery(sql);
while (set.next()) {
int id = set.getInt(1);
int age = set.getInt(2);
String name = set.getString(3);
System.out.println(id + "\t" + age + "\t" + name);
}
// 关闭连接
set.close();
statement.close();
connection.close();
}
}
删除/更改/添加表里的数据
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
public class test2 {
public static void main(String[] args) throws Exception, ClassNotFoundException {
Properties info = new Properties();
info.load(new FileInputStream("src\\jdbc.properties"));
String user = info.getProperty("user");
String password = info.getProperty("password");
String driver = info.getProperty("driver");
String url = info.getProperty("url");
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取链接
Connection connection = DriverManager.getConnection(url,user,password);
// 执行语句
String sql ="delete from user where id = 8";
//删除
//"update user set name ='hhh' where id = 3";更改
//"insert into user values (null ,'15','jjj')";添加
Statement statement = connection.createStatement();
int update = statement.executeUpdate(sql);
System.out.println(update>0?"success":"failure");
statement.close();
connection.close();
}
}