2008
10-3
10-3
PHP总有其局限性,比如解释型语言在速度上的弱点,制约了它在效率方面的发挥。facebook开放了源代码,其底层大都是c来编写,而我现在计划用Java为一些服务写后台,这是我的第一个Java程序,希望大家多批评,虽然上边依然有太多php的影子。
- import java.sql.*;
- /*
- * Java Mysql数据库连接类
- * 我的第一个java程序
- */
- public class MysqlConn
- {
- private String dsn = "jdbc:mysql://localhost:3306/test";
- private String username = "root";
- private String password = "123456";
- private Connection conn = null;
- private Statement stmt = null;
- private ResultSet rs = null;
- public void MysqlConn()
- {
- }
- //初始化连接参数
- public void SetDsn( String Dsn )
- {
- this.dsn = Dsn;
- }
- //初始化用户名密码
- public void SetUserPass( String Username , String Password )
- {
- this.username = Username;
- this.password = Password;
- }
- //连接函数
- public void Conn()
- {
- try
- {
- //加载Connetc/J驱动
- //Class.forName("com.mysql.jdbc.Driver");
- Class.forName("org.gjt.mm.mysql.Driver");
- //开始连接
- this.conn = DriverManager.getConnection( this.dsn , this.username , this.password );
- this.stmt = this.conn.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE , ResultSet.CONCUR_UPDATABLE );
- }
- catch(SQLException ex)
- {
- System.out.println("Error : " + ex.toString());
- System.out.println("没有找到JDBC/ODBC驱动程序!");
- System.exit(0);
- }
- catch(Exception e)
- {
- System.out.println("Errors: " + e.toString());
- System.exit(0);
- }
- }
- //返回结果集
- public ResultSet sqlQuery( String sql )
- {
- try
- {
- this.rs = this.stmt.executeQuery( sql );
- }
- catch (SQLException ex)
- {
- System.out.println("Error : " + ex.toString());
- System.exit(0);
- }
- catch (Exception ex)
- {
- System.out.println("Error : " + ex.toString());
- System.exit(0);
- }
- return rs;
- }
- //执行 update,insert之类
- public void Exec( String sql )
- {
- try
- {
- this.stmt.executeUpdate( sql )
- }
- catch (SQLException ex)
- {
- System.out.println("Error : " + ex.toString());
- System.exit(0);
- }
- catch (Exception ex)
- {
- System.out.println("Error : " + ex.toString());
- System.exit(0);
- }
- }
- }