注意:以上使用log4j日志记录异常
查询
package cn.jbit.jdbctest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
/**
* 使用Statement的executeQuery()方法查询并输出狗狗信息。
* @author
*/
public class Test5 {
private static Logger logger = Logger.getLogger(Test5.class.getName());
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
// 1、加载驱动
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
logger.error(e);
}
try {
// 2、建立连接
conn = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;DatabaseName=epet",
"jbit", "bdqn");
// 3、查询并输出狗狗信息
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from dog");
System.out.println("\t\t狗狗信息列表");
System.out.println("编号\t姓名\t健康值\t亲密度\t品种");
while (rs.next()) {
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getInt("health")+ "\t");
System.out.print(rs.getInt("love")+"\t");
System.out.println(rs.getString("strain"));
}
} catch (SQLException e) {
logger.error(e);
} finally {
// 4、关闭Statement和数据库连接
try {
if (null != rs) {
rs.close();
}
if (null != stmt) {
stmt.close();
}
if (null != conn) {
conn.close();
}
} catch (SQLException e) {
logger.error(e);
}
}
}
}
示例:使用PreparedStatement避免SQL注入
package cn.jbit.jdbctest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.log4j.Logger;
/**
* 使用PreparedStatement更新狗狗信息。
* @author
*/
public class Test7 {
private static Logger logger = Logger.getLogger(Test7.class.getName());
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
// 1、加载驱动
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
logger.error(e);
}
try {
// 2、建立连接
conn = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;DatabaseName=epet",
"jbit", "bdqn");
// 3、更新狗狗信息到数据库
String sql="update dog set health=?,love=? where id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 80);
pstmt.setInt(2, 15);
pstmt.setInt(3, 1);
pstmt.executeUpdate();
pstmt.setInt(1, 90);
pstmt.setInt(2, 10);
pstmt.setInt(3, 2);
pstmt.executeUpdate();
logger.info("成功更新狗狗信息!");
} catch (SQLException e) {
logger.error(e);
} finally {
// 4、关闭Statement和数据库连接
try {
if (null != pstmt) {
pstmt.close();
}
if (null != conn) {
conn.close();
}
} catch (SQLException e) {
logger.error(e);
}
}
}
}