连接
public Connection con;
public Statement statement;
//驱动程序名
public String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
public String url = "jdbc:mysql://localhost:3306/mydata";
//MySQL配置时的用户名
public String user = "root";
//MySQL配置时的密码
public String password = "root";
try {
//加载驱动程序
Class.forName(driver);
//连接MySQL数据库!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
statement = con.createStatement();
else
System.out.println("连接失败");
}catch(ClassNotFoundException e) {
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("连接成功");
}
增加(insert)/修改(update)/删除(delete)
String sqlStr = "UPDATE stutable SET name='名字' WHERE ID = '30'";
//sqlStr = "INSERT INTO stutable (name,age) VALUES ('名字','25')";
//sqlStr = "DELETE FROM stutable WHERE ID = '30'";
int rs = 0;
try {
rs = statement.executeUpdate(sqlStr);
if(rs == 1){
System.out.println("操作成功");
}else{
System.out.println("操作失败");
}
} catch (SQLException e) {
e.printStackTrace();
}
查询(selete)
String sqlStr = "SELECT * FROM stutable WHERE ID = '30'";
ResultSet rs = null;
try {
rs = statement.executeQuery(sqlStr);
if(rs.next()){ //while(rs.next())
String str_ID = rs.getString("ID");
String str_name = rs.getString("name");
String str_age = rs.getString("age");
}else {
System.out.print("不存在");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
}