JDBC和DBUtil连接,javascript的Ajax请求
JDBC数据库连接
//1.导入驱动jar包
//2.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//3.获取数据库连接对象
Connection conn = DriverManager.getConnection("url", "username", "password");
//4.定义sql语句
String sql = "update account set balance = 500 where id = 1";
//5.获取执行sql的对象 Statement
Statement stmt = conn.createStatement();
//6.执行sql
int count = stmt.executeUpdate(sql);
//7.处理结果
System.out.println(count);
//8.释放资源
stmt.close();
conn.close();
DBUtil数据库连接
public static QueryRunner getRunner() {
return new QueryRunner(dataSource);
}
static {
//InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("db.properties");
//类名.class Class.forName("包名.类名") ClassLoader 前三种结果相同
Properties prop = new Properties();
try {
prop.load(is);
driver = prop.getProperty("jdbc.driver");
url = prop.getProperty("jdbc.url");
username = prop.getProperty("jdbc.username");
password = prop.getProperty("jdbc.password");
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
} catch (IOException e) {
e.printStackTrace();
}
}
//使用
DBUtil.getRunner().query(sql, new BeanListHandler<>(NewsCollect.class), userId);
备注:静态代码块在类记载的时候执行,而且只执行一次。一般用来对类初始化数据的定义。调用类的静态变量、调用类的静态方法、创建对象时,静态代码块会执行
javascript的Ajax请求
<script type="text/javascript">
window.onload=function(){
//1.获取a节点,并为其添加onclick响应函数
document.getElementsByTagName("a")[0].onclick=function(){
//3.创建一个XMLHttpRequest对象
var request=new XMLHttpRequest();
//4.准备发送请求的数据:url
var url=this.href +"?time="+new Date();
var method="GET";
//var method="POST"
//5.调用xmlhttprequest对象的open方法
request.open(method,url);
//request.setRequestHeader("ContentType","application/x-www-form-urlencoded");
//6.调用xmlhttprequest对象的send方法,get请求参数为null
request.send(null);
//request.send("name='aaa'");
//7.为xmlhttprequest对象添加onreadystatechange响应函数
request.onreadystatechange=function(){
//8.决断响应是否完成:xmlhttprequest对象的readystate属性值为4
if(request.readyState==4){
//9.再决断响应是否可用:xmlhttprequest对象status属性值为200
if(request.status==200){
//10.打印响应结果:responseText
alert(request.responseText);
}
}
}
//取消a节点的默认行为
return false;
}
}
}
</script>