java JDBC-statement接口實現簡單的sql語句調用

最後必需要關閉兩個鏈接mysql

public class Demo2 {

public static void main(String[] args) {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","dyl123");

        //使用statement接口實現簡單sql調用
        Statement stmt=conn.createStatement();

        String sql="insert into t_user(username,pwd,regTime) values ('趙六',66666,now()) ";

        //傳入外界參數,須要拼字符串
        String name="錢七";
        String sql2="insert into t_user(username,pwd,regTime) values('"+name+"',6666,now())";

        stmt.execute(sql);
        stmt.execute(sql2);

    //sql注入,傳參的幾種拼接方式,若是代碼傳參有問題,則數據庫會被侵入
        String id="4";

        String sql3="delete from t_user where id=4";
        String sql4="delete from t_user where id='"+id+"'";
        String sql5="delete from t_user where id="+id;

        stmt.execute(sql4);

    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {

        e.printStackTrace();
    }finally {
        try {
            if(null!=conn)
            {
                stmt.close();
            }
            try {
            if(null!=stmt)
            {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

}

}
}
相關文章
相關標籤/搜索