Extjs连接Mysql数据库, 在这里是通过JSP来连接Extjs和数据库的。
首先: JSP可以连接数据库, 并能成功访问, 其中最最重要的就是编码问题, 这个以后再说。
代码如下:
Connection C = null;
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
System.out.println("check the mysql driver");
}
catch (Exception E) {
System.out.println("Unable to load driver.");
}
try {
C = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/teacher?user=root&password=mysql");
Statement s=C.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
System.out.println("check the mysql connect");
ResultSet rs=s.executeQuery("select * from tes");
System.out.println("<table border=1>");
System.out.println(rs.getRow());
while(rs.next()){
System.out.print(rs.getString("name"));
%>
<%
}
rs.close();
s.close();
C.close();
}
catch (SQLException E) {
System.out.println("SQLException: " + E.getMessage());
System.out.println("SQLState: " + E.getSQLState());
System.out.println("VendorError: " + E.getErrorCode());
}
其次: 将访问的数据配置到相应的fields里。 因为store的格式为:[{},{}], 所以可以把[]分开,且在后面的]添加“,{}”, 即现在多了一项为空的数据,其实可以在json访问的时候少选一项即可。
代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ page import="java.sql.*"%>
[
<%! String name= ""; //请勿这样设置 String name;
String age= "";
String sex= "";
%>
<%
Connection C = null;
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
System.out.println("check the mysql driver");
}
catch (Exception E) {
System.out.println("Unable to load driver.");
}
try {
C = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/teacher?user=root&password=mysql");
Statement s=C.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
System.out.println("check the mysql connect");
ResultSet rs=s.executeQuery("select * from tes");
System.out.println("<table border=1>");
System.out.println(rs.getRow());
while(rs.next()){
name = rs.getString(2);
age = rs.getString(1);
sex = rs.getString(3);
%>
{name:"<%=name%>", age:"<%=age%>", sex:"<%=sex%>"},
<%
}
rs.close();
s.close();
C.close();
}
catch (SQLException E) {
System.out.println("SQLException: " + E.getMessage());
System.out.println("SQLState: " + E.getSQLState());
System.out.println("VendorError: " + E.getErrorCode());
}
%>
{}]
最后: Extjs通过JSP连接的数据访问方式
Ext.onReady(function(){ //Json 使用
//var urlJsp = "http://localhost:8086/ext/Excmple/Store/JsonStore.jsp";
var urlJsp = "http://localhost:8086/testMysql/index.jsp";
var _store = new Ext.data.JsonStore({
autoLoad:true, //设置为自动加载,或者使用_store.load(),具体情况而定
proxy: new Ext.data.HttpProxy({url:urlJsp}),
fields:["name", "sex", "age"]
});
_store.on("load", function(_store){
alert("test "+_store.getCount());
var str = "";
for(var i=0; i<_store.getCount()-1 ; i++)
str += _store.getAt(i).get("name")+" "+_store.getAt(i).get("sex")+" "+_store.getAt(i).get("age")+ "/n";
alert(str);
Ext.Msg.alert("show", "the type of age 是: " + typeof(_store.getAt(0).get("age")));
});
//_store.load();
});