首页 > 代码库 > java 使用 mysql

java 使用 mysql

首先下载mysql的jdbc驱动。

然后新建一个Datamanager类:

public class MysqlManager extends DataManager {
    
    static private final MysqlManager MYSQL = new MysqlManager();
    
    static private final String URL ="jdbc:mysql://localhost:3306/test";
    static private final String DRIVER = "com.mysql.jdbc.Driver"; 
    private final String userName ="root";
    private final String password="root";
    
    /**数据库操作对象**/
    Statement m_readStm = null;
    Connection m_con = null;
    
    static public MysqlManager getInstance(){
        return MYSQL;
    }

    
    private MysqlManager(){
        try {
            Class.forName(DRIVER);// 加载Mysql数据驱动  
           
            m_con = DriverManager.getConnection(URL, userName, password);// 创建数据连接  
            //创建数据库读取状态
            m_readStm = m_con.createStatement(
                    ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
        }catch (ClassNotFoundException | SQLException e ) {  
            System.err.println("数据库连接失败!  " + e.getMessage());
        }
    }
}

还需要添加一个close函数,用于关闭数据库链接。