import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTest {
public static void main(String[] args) throws ClassNotFoundException,SQLException {
//1.加载数据库驱动(提供一个jdbc的数据库驱动的名称)
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接
String url = "jdbc:mysql:///gooddb";
Connection conn = DriverManager.getConnection(url, "root", "root");
//3.获取Statment对象(该对象用于对数据库进行CRUD操作)
Statement stat = conn.createStatement();
//4.执行SQL语句
//String sql = "INSERT INTO t_class(classname) VALUES('java07')";
String sql = "UPDATE t_class SET classname = 'sql01' WHERE id = 2";
//executeUpdate()方法用于执行insert、update、delete语句,该方法返回影响数据库的行数
int rows = stat.executeUpdate(sql);
if(rows > 0) {
System.out.println("操作成功!");
}
//5.释放连接
stat.close();
conn.close();
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SelectTest {
public static void main(String[] args) {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///gooddb","root","root");
stat = conn.createStatement();
String sql = "select id,classname from t_class";
//获取结果集对象
rs = stat.executeQuery(sql);
while(rs.next()) {
//int id = rs.getInt("id");
int id = rs.getInt(1);
//String name = rs.getString("classname");
String name = rs.getString(2);
System.out.println("id:" + id + "\tclassname:" + name);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//释放连接
try {
if(rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(stat != null) {
stat.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}