import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Scanner;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
public class JDBCDemo {
private static final String URL="jdbc:mysql://localhost:3306/jdbc";//URL一般都是大写,不让它改变
private static final String USERNAME="root";
private static final String PWD="wangjie";
private static Scanner input;
URL:数据库连接字符串,一般用大写,不让它改变
USNAME:数据库用户名,mysql的数据库名一般为root
PWD:数据库的密码
public static void update() {//增删改数据
对数据库表的数据进行增删改
Statement stmt=null;
Connection connection=null;
try {
Class.forName("com.mysql.jdbc.Driver");//加载具体的驱动类
//1、导入驱动,加载具体的驱动类
connection=DriverManager.getConnection(URL, USERNAME, PWD);
//2、与数据库建立连接
stmt=(Statement) connection.createStatement();
//3、发送sql,执行(增删改、查)
//String sql="insert into student value(1,'zs',23,'s1')";
//增加数据
//String sql="update student set STUNAME='ls' where STUNO=1";
//更改数据
String sql="delete from student where stuno=1";
//删除数据
int count=stmt.executeUpdate(sql);
//增删改用executeUpdate,查询用executeQuery
//4、处理结果
if(count>0) {
System.out.println("操作成功!");
}
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
关闭
finally {
try {
if(stmt!=null)stmt.close();//对象.方法 一般不建议直接写,要加上判断是否为空,如果对象为空,就会报空指针,出现异常加try{}catch
if(connection!=null)connection.close() ;//为了防止空指针异常,用if来判断是否为空指针
//无论程序正常或者异常,都需要进行关闭,关闭释放资源在finally里面写
}catch(SQLException e) {
e.printStackTrace();
}
}
}
//查询数据库
public static void query() {
Statement stmt=null;
Connection connection=null;
ResultSet rs=null;
try {
//1、导入驱动,加载具体的驱动类
Class.forName("com.mysql.jdbc.Driver");//加载具体的驱动类
//2、与数据库建立连接
connection=DriverManager.getConnection(URL, USERNAME, PWD);
//3、发送sql,执行(增删改、查)
stmt=(Statement) connection.createStatement();
rs=(ResultSet) stmt.executeQuery(sql);//返回结果集
//4、处理结果
while(rs.next()) {
int sno=rs.getInt("stuno");//不推荐用下标名
String sname=rs.getString("stuname");
System.out.println(sno+"--"+sname);
}
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(rs!=null) rs.close();//查询:先开的后关,后开的先关
if(stmt!=null)stmt.close();
if(connection!=null)connection.close() ;
}catch(SQLException e) {
e.printStackTrace();
}
}
}
主函数调用
public static void main(String[] args) {
query();
//update();
}
}