PreparedStatement預編譯
在學習SQL語句時,爲了防止在進行查詢時SQL注入,需要將SQL語句參數化,就需要用到connection類的preparestatement方法進行預編譯,(創建一個 PreparedStatement 對象來將參數化的 SQL 語句發送到數據庫)
String select="SELECT * FROM USER WHERE name='maqi ' and password='123'";
String select="SELECT * FROM USER WHERE name='maqi ' and password='123'or '1=1'";
但表中實際存在的是
分別執行後,結果爲:執行成功
maqi 123
true 1
maqi登錄成功! 密碼爲123 num=1
maqi 123’or ‘1=1
true 13
maqi登錄成功! 密碼爲123’or ‘1=1 num=13雖然兩條SQL語句查找的結果不同,但證明了要查找的結果“存在”,用在登錄查找是會是得不存在的用戶也能登陸成功,雖然不是我們想要查找的結果,但是在SQL語句編譯時改變了對該語句的理解,變成了對SQL語句的理解,不是我們原來的理解.這就是SQL注入。解決辦法爲使SQL參數化,用preparedStatement進行預編譯。具體代碼實現如下:
Connection coon=SQLManager.newInstabce().getConn();
String name=textAreaName.getText();
String password=textAreaPassword.getText();
try {
PreparedStatement preparedStatement = coon.prepareStatement("select * from user where name=? and password=?");
preparedStatement.setString(1, name);
preparedStatement.setString(2, password);
ResultSet set=preparedStatement.executeQuery();
set.last();
int num=set.getRow();
System.out.println("查詢的結果"+num);
if (num>0) {
System.out.println(name+"登錄成功! 密碼爲"+password+" num="+num);
}else{
System.out.println("該用戶不存在,請註冊! num="+num);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
分別輸入 maqi–123和maqi–1234‘or 1=’1
運行結果:
執行成功
查詢的結果1
maqi登錄成功! 密碼爲123 num=1
查詢的結果0
該用戶不存在,請註冊! num=0
事務
事務(一組不可拆分的操作)
String name=textAreaNmae.getText();
String password=textAreaPassword.getText();
Connection coon=SQLManager.newInstabce().getConn();
String sql1="insert into user(name,password)values('星星','123')";
String sql2="insert into user(name,password)values('猴子','124')";
String sql3="insert into user(name,password)values('貓','125')";
String sql4="insert into user(name,password)values('魚','5555')";
String sql5="insert into user(name,password)values('狗','8888')";
try {
Statement state=coon.createStatement();
//數據庫連接默認爲每一條語句都是一個事務,會單獨執行
//首先設置connection不會自動提交
coon.setAutoCommit(false);
state.execute(sql1);
state.execute(sql2);
state.execute(sql3);
state.execute(sql4);
state.execute(sql5);
// state.addBatch(sql1);
// state.addBatch(sql2);
// state.addBatch(sql3);
// state.addBatch(sql4);
// state.addBatch(sql5);
// state.executeBatch();
coon.commit();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Web項目
利用eclipse中的插件tomcat編寫網頁
將編寫服務器連接到數據庫
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.ParameterParser;
/**
* Servlet implementation class MyTestServerlet
*/
@WebServlet("/MyTestServerlet")
public class MyTestServerlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyTestServerlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String userName = request.getParameter("userName");
String password = request.getParameter("password");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (userName==null&&password==null) {
System.out.println("userName=null password=null");
}else{
userName=Encoding.doEncoding(userName);
System.out.println("提交了用戶和密碼,用戶名:"+userName+" 密碼:"+password);
String s="提交了用戶信息,用戶名稱:"+userName+" 密碼:"+password;
// 讓瀏覽器以utf-8編碼格式解析
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.getWriter().append(s);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
SQLManager類
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLManager {
public Connection conn;
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public Statement state;
public Statement getState() {
return state;
}
public void setState(Statement state) {
this.state = state;
}
// 單例設計模式
private static SQLManager manager;
public static synchronized SQLManager newInstabce() {
if (manager == null) {
manager = new SQLManager();
}
return manager;
}
private SQLManager() {
// 鏈接數據庫驅動
String driver = "com.mysql.jdbc.Driver";
// URL指向要訪問的數據庫名
String url = "jdbc:mysql://localhost:3306/calzz";
// MySQL配置使得用戶名
String user = "root";
// Java連接MySQL時配置的密碼
String password = "2012163";
try {
Class.forName(driver);// 加載驅動
// 與數據庫建立連接
conn = DriverManager.getConnection(url, user, password);
if (!conn.isClosed()) {
// 數據庫操作類
state = conn.createStatement();
String creatTable = "CREATE TABLE if not exists user (id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,name varchar(20) BINARY NOT NULL,password int(6) NOT NULL )";
state.execute(creatTable);
// String sql="insert into
// student(name,sex,age)values('張三',1,18)";
//// state.execute(sql);
// String update="update student set name='王五' where id=7";
// state.execute(update);
// String delete="delete from student where id=8";
// state.execute(delete);
// String select="select * from student";
//// state.executeQuery(select);
// ResultSet set=state.executeQuery(select);
// set.first();
// while (!set.isLast()) {
// System.out.println(set.getString("name"));
// set.next();
// }
//
System.out.println("執行成功");
} else {
System.out.println("請打開數據庫");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
encoding類
import java.io.UnsupportedEncodingException;
public class Encoding {
public static String doEncoding(String string) {
try {
byte[] array = string.getBytes("ISO-8859-1");
string = new String(array, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return string;
}
}