一,简单的连接数据库,读取,和更改
ublic class TestJDBC {
public static void main(String[] args) {
read();
update();
}
private static void read() {
Connection conn = null;
// 3、建立语句
Statement stmt = null;
ResultSet rs = null;
try {
// 1、注册
Class.forName("com.mysql.jdbc.Driver");
// 2、连接
String url = "jdbc:mysql://localhost:3306/jdbctest?user=root&password=root";
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
//用select * 程序的可读性不高,因为别人阅读你代码,它不知道你每列的查的是什么,
//另外如果有人修改了数据列的顺序,那么你代码就出错
//String sql = "select * from student";
//String sql="select id,age,name from student ";
//给列起别名
String sql="select id,age,name studentName from student ";
rs = stmt.executeQuery(sql);
// 4、结果处理
//System.out.println("id\tname\tage\t");
//如果访问列前不执行rs.next,会有异常:Before start of result set
while (rs.next()) {
//如果按照位置调用getXxx(),那么就会有问题,可能别人进行了修改
// System.out.printf("%-3s", rs.getInt(1));
// System.out.printf("%-12s", rs.getString(2));
// System.out.printf("%-3s\n", rs.getInt(3));
//按照列名去调用
//如果按照列名去访问,就跟位置无关了
System.out.printf("%-3s", rs.getInt("id"));
//当我们给列起了别名时,我们要用别名
//System.out.printf("%-12s", rs.getString("name"));
System.out.printf("%-12s", rs.getString("studentName"));
System.out.printf("%-3s\n", rs.getInt("age"));
// System.out.print(rs.getInt(1));
// System.out.print(rs.getString(2));
// System.out.println(rs.getInt(3));
}
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
// 5、释放资源
// try {
// if (null!=rs) {
//
// rs.close();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// try {
// if (null!=stmt) {
//
// stmt.close();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// try {
// if (null!=conn) {
//
// conn.close();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
try {
if (null != rs) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (null != stmt) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (null != conn) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// try {
// if (null != rs) {
// rs.close();
// }
// } catch (SQLException e) {//不发生异常,那么connection等就没被关闭了。
// try {
// if (null != stmt) {
// stmt.close();
// }
// } catch (SQLException e) {
// e.printStackTrace();
// } finally {
// try {
// if (null != conn) {
// conn.close();
// }
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
// }
}
}
private static void update() {
Connection conn = null;
// 3、建立语句
Statement stmt = null;
try {
// 1、注册
Class.forName("com.mysql.jdbc.Driver");
// 2、连接
String url = "jdbc:mysql://localhost:3306/jdbctest?user=root&password=root";
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
String sql = "update student set name='test2' where id=9";
//rs = stmt.executeQuery(sql);
int result=stmt.executeUpdate(sql);
// 4、结果处理
//System.out.println("受影响的行数:"+result);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
二,数据库的关闭
finally {
// 5、释放资源
try {
if (null != stmt) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (null != conn) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
System.out.println("更新成功");
}
}
三,注入漏洞
public class SqlInject {
public static void main(String[] args) {
read("' or 1=1 or '");//sql注入语句
}
private static void read(String userName) {
Connection conn = null;
// 3、建立语句
Statement stmt = null;
ResultSet rs = null;
try {
String url = "jdbc:mysql://localhost:3306/jdbctest?user=root&password=root";
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
String sql="select id,age,name studentName from student where name='"+userName+"'";
System.out.println(sql);
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.printf("%-3s", rs.getInt("id"));
System.out.printf("%-12s", rs.getString("studentName"));
System.out.printf("%-3s\n", rs.getInt("age"));
}
} catch (SQLException e1) {
e1.printStackTrace();
} finally {
避免的方法:
* @author 淮源之星
* 类说明:该类主要用来展示如何用PreparedStatement来避免Sql注入
*
*/
public class AntiSqlInjectUsingPreparedStament {
public static void main(String[] args) {
read("' or -3 or '");// sql注入语句
}
private static void read(String userName) {
Connection conn = null;
// 3、建立语句
CallableStatement cstmt = null;
try {
conn =JDBCUtils.getConnection();
//建立语句
cstmt = conn.prepareCall("{call proc_insert_test(?,?)}");
cstmt.setString(1, "hujingtao");//给问号设置
cstmt.setInt(2, 76);
int count = cstmt.executeUpdate();//执行更新
System.out.println("受影响的行数:" + count);
} catch (SQLException e1) {
e1.printStackTrace();
} finally {
JDBCUtils.free(null, cstmt, conn);
}
}
}
四,连接数据库的几种方法
1,// 1、注册
Class.forName("com.mysql.jdbc.Driver");
// 2、连接
String url = "jdbc:mysql://localhost:3306/jdbctest?user=root&password=root";
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
2,public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql = "";
try {
Driver drv = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(drv);
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=root");
stmt = conn.createStatement();
sql = "select * from student";
rs = stmt.executeQuery(sql);
JdbcUtils.printResult(rs);
} catch(Exception ex) {
ex.printStackTrace();
} finally {
JdbcUtils.free(rs, stmt, conn);
}
}
3,public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql = "";
try {
File f = new File("test.properties");
InputStream in = new BufferedInputStream(new FileInputStream(f));
Properties p = new Properties();
p.load(in);
in.close();
Class.forName(p.getProperty("jdbc.drivers"));
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=root");
stmt = conn.createStatement();
sql = "select * from student";
rs = stmt.executeQuery(sql);
JdbcUtils.printResult(rs);
} catch(Exception ex) {
ex.printStackTrace();
} finally {
JdbcUtils.free(rs, stmt, conn);
}
}
五,preparedStatement用法
public static void main(String[] args) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "";
try {
conn = JdbcUtils.getConnection();
sql = "select * from student where id=?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1,1);
rs = stmt.executeQuery();
System.out.println("第一次执行:");
JdbcUtils.printResult(rs);
stmt.setInt(1,2); //stmt.setString(),stmt.setFloat()
rs = stmt.executeQuery(); //stmt.executeUpdate()
System.out.println("第二次执行:");
JdbcUtils.printResult(rs);
} catch(Exception ex) {
ex.printStackTrace();
} finally {
JdbcUtils.free(rs, stmt, conn);
}
}
六,CallableStatement用法;
ublic static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
CallableStatement cstmt = null;
ResultSet rs = null;
String sql = "";
try {
conn = JdbcUtils.getConnection();
stmt = conn.createStatement();
sql = "select * from student";
rs = stmt.executeQuery(sql);
System.out.println("调用存储过程前查询数据:");
JdbcUtils.printResult(rs);
// 调用存储过程
sql = "{call proc_insert_test(?,?)}";
cstmt = conn.prepareCall(sql);
cstmt.setString(1, "sunqi");
cstmt.setInt(2, 33);
cstmt.executeUpdate();
sql = "select * from student";
rs = stmt.executeQuery(sql);
System.out.println("\n\n\n调用存储过程后查询数据:");
JdbcUtils.printResult(rs);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
JdbcUtils.free(rs, cstmt, conn);
}
}
七,自己写的连接数据库和关闭数据库的类
public class JdbcUtils {
private static String url = "jdbc:mysql://localhost:3306/jdbctest";
private static String user = "root";
private static String password = "root";
private static String driver = "com.mysql.jdbc.Driver";
private JdbcUtils() {
}
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, user, password);
}
public static void free(ResultSet rs,Statement stmt,Connection conn){
try {
if (rs!=null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if (stmt!=null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if (null!=conn) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public static void printResult(ResultSet rs) {
try {
//1、列头
ResultSetMetaData rsd=rs.getMetaData();
String spaceString="";
for (int i = 1; i <= rsd.getColumnCount(); i++) {
System.out.printf("%12s", rsd.getColumnLabel(i));
spaceString+="---------------";
}
System.err.println("\n"+spaceString);
//表内容
while (rs.next()) {
for (int i = 1; i <= rsd.getColumnCount(); i++) {
System.out.printf("%12s", rs.getObject(i));
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}