1 实现MySQL支持
1.1 必要条件
1.2 方法 1a: mySQL ‘inline’
1.3 方法 1b: 将mysql的配置信息保存在.properties文件中
+ 1.3.1 步骤一: 设置database.properties文件
+ 1.3.2 步骤二: Red5端的JAVA代码
1.4 方法2: JNDI (数据连接池)
+ 1.4.1 步骤一:定义数据库资源
+ 1.4.2 步骤二:挂接到你的应用程序
+ 1.4.3 步骤三:Red5端的java程序
* 2 使用MySQL
1.实现mySQL支持
1.1 必要条件
>> 从http://dev.mysql.com获得mysql-connector-java-3.*.*-bin.jar并将其放置在{TOMCAT_HOME}\common\lib\中
>> 当然,还需要一个运行的mySQL数据库
1.2 方法1a,mySQL ‘inline’
>> 注意,这个方法只是实现测试功能,不具备实用价值
private void logMessage(String msg) {
Statement stmt = null;
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://host.xxxx.com/dbname","username","password");
stmt = conn.createStatement();
stmt.execute(
"INSERT INTO log_lobby_chat (message) "
+ "VALUES ('" + msg.replace("'","") + "')");
stmt.close();
stmt = null;
conn.close();
conn = null;
} catch (SQLException ex) {
log.debug("SQLException: " + ex.getMessage());
log.debug("SQLState: " + ex.getSQLState());
log.debug("VendorError: " + ex.getErrorCode());
}
}
1.3 方法1b,将mysql的配置信息保存在.properties文件中
本方法将从database.properties文件中读取mysql的配置信息,然后再应用这些数据讲Tomcat连接到mysql数据库
步骤一:设置database.properties
将下列代码保存成database.properties,并把它放到{RED5_HOME}所设置的WEB-INF目录下
jdbc.drivers = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://yourmysqlhost.domain.com/yourdatabasenamehere
jdbc.username = your_username_here
jdbc.password = your_password_here
步骤二:java代码
import java.io.*;
import java.io.FileInputStream;
import java.util.Properties;
import java.sql.*;
private static Connection getConnection() throws SQLException, IOException
{
Properties props = new Properties();
// 从{TOMCAT_HOME}\webapps\{RED5_HOME}\WEB-INF\目录中打开database.properties
FileInputStream in = new FileInputStream(System.getProperty("red5.config_root") + "/database.properties");
props.load(in);
in.close();
// 获取Drivers字符串
String drivers = props.getProperty("jdbc.drivers");
if(drivers != null) {
System.setProperty("jdbc.drivers", drivers); // If drivers are not set in properties, set them now.
// Class.forName("com.mysql.jdbc.Driver").newInstance();
}
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
return DriverManager.getConnection(url, username, password);
}
public void logMessage(String msg) {
Statement stmt = null;
try {
Connection conn = getConnection(); // Get connection from properties file
// Do something with the Connection
stmt = conn.createStatement();
stmt.execute(
"INSERT INTO log_chatroom (message) "
+ "VALUES ('" + msg.replace("'","''") + "')");
stmt.close();
stmt = null;
conn.close();
conn = null;
} catch (IOException ex) {
log.error("SQLException: " + ex.getMessage());
} catch (SQLException ex) {
log.error("SQLException: " + ex.getMessage());
log.error("SQLState: " + ex.getSQLState());
log.error("VendorError: " + ex.getErrorCode());
}
}
1.4 JNDI (数据连接池)
本方法通过数据连接池来进行数据连接,所有的Tomcat数据库资源将被定义在数据连接池中供应用程序使用。
重要:
删除{RED5_HOME}/WEB-INF/lib/目录下的JAR文件(如果这些文件存在,可能会引起错误,你可能会得到以下错误信息’JNDI Name java:comp is not bound in this Context’)
步骤一,定义数据库资源
将下面的<Resource>标签增加到{TOMCAT_HOME}\conf\server.xml
<Server>
<Service name="Catalina">
<Engine defaultHost="localhost" name="Catalina">
<Host appBase="webapps" name="localhost">
<Context path="/red5-0.6rc1">
<WatchedResource>/usr/local/apache-tomcat-5.5.20/conf/context.xml</WatchedResource>
<Resource
name="jdbc/your_ref_name"
type="javax.sql.DataSource"
url="jdbc:mysql://yourmysqlhost.domain.com/your_database_name?autoReconnect=true"
username="your_username"
password="your_password"
driverClassName="com.mysql.jdbc.Driver"
maxIdle="2"
maxWait="5000"
maxActive="4"/>
</Context>
</Host>
</Engine>
</Service>
</Server>
步骤二:挂接到应用程序
在{RED5_HOME}\WEB-INF\web.xml中的<web-app>标签间增加以下代码
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/your_ref_name</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
请确定<res-ref-name> 标签所包含的值与第一步中<Resource name=”"> 所设定的相一致。
步骤三:Red5端的java程序
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Application extends ApplicationAdapter implements IPendingServiceCallback, IStreamAwareScopeHandler {
private static final Log log = LogFactory.getLog(Application.class);
private DataSource dataSource;
@Override
public boolean appStart(IScope scope) {
// init your handler here
try {
Context init = new InitialContext();
Context ctx = (Context) init.lookup("java:comp/env");
dataSource = (DataSource) ctx.lookup("jdbc/your_datebase_name");
log.debug("JNDI OK!!!");
}
catch (NamingException ex) { // Error handling here
log.error("JNDIException: " + ex.getMessage());
}
Connection con = null;
try {
synchronized (dataSource) {
con = dataSource.getConnection();
}
PreparedStatement pstmt = con.prepareStatement("INSERT INTO log_chatroom (message) VALUES (?)");
pstmt.setString(1, "This is a test!");
ResultSet results = pstmt.executeQuery();
if (results != null) results.close(); // You can loop through records if you use a SELECT query
if (pstmt != null) pstmt.close();
if (con != null) con.close();
}
catch (Exception ex)
{ // Exception handling here
}
return true;
}
}
2.使用Mysql
简单的查询,不需要从数据库获取数据
Statement stmt = conn.createStatement();
stmt.execute("SOME SQL QUERY");
如果你需要从数据库获取数据,可以使用以下代码
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SOME SQL QUERY");
// if you dont loop over the result set, make sure you call result.next() first
// otherwise you'll end up with an empty set!
while (result.next()) {
// youre code comes here
// getXXX use to retreive the Data from a resultset, getInt, getString and so on
// getXXX can be used with the columnname or the column position (int)
System.out.println(result.getString("my_mysql_columnName"));
}
本文来源于 冰山上的播客 http://xinsync.xju.edu.cn , 原文地址:http://xinsync.xju.edu.cn/index.php/archives/1208
本文来源于 冰山上的播客 http://xinsync.xju.edu.cn , 原文地址:http://xinsync.xju.edu.cn/index.php/archives/1208