打开Tomcat 6.0目录conf 文件夹里的context.xml ,在<Context reloadable="true">标签下写入
<Resource name="jdbc/mysqlds" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="admin"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1/blog" />
并把驱动JAR包把到Tomcat 6.0下lib文件夹里,然后再JAVA类用这段代码获取:
DataSource ds = null;
try {
// 通过context.xml文件,设定数据源对象的名字,并获取数据源对象。
Context context = new InitialContext();
ds = (DataSource) context.lookup("java:/comp/env/jdbc/mysqlds");
} catch (Exception e) {
System.out.println("获取数据库出错");
}
Connection conn = ds.getConnection();
再通过QueryRunner类操作:
SQLQueryRunner qr = new QueryRunner(ds);
int result = qr.update(conn,sql,String[]);//qr.update(sql,String[]);//调用它的update方法完成SQL的运行并返回更新数. insert into / update / delete
List<Blog> list = qr.query(sql, new BeanListHandler(Blog.class));//查询。Blog.class为javabean:Blog.java。 存放在List里面。
如果报了这个错The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files
是jdk版本的问题.我之前在jdk8上报了这个错.换到jdk6后正常.
详情看 http://blog.csdn.net/oizz01/article/details/17359941
@@@