SQL数据库也程序的连接

来源:互联网 发布:自动签到脚本 python 编辑:程序博客网 时间:2024/05/22 04:25
    private String url = "jdbc:mysql://localhost:3306/javademo";    private String user = "root";    private String password = "123456";    /** 加载SQL驱动 */    public void startSQLDriver() {        try {            Class.forName("com.mysql.jdbc.Driver");        } catch (ClassNotFoundException e) {            e.printStackTrace();        }    }    /** 建立连接Connection */    public Connection getConnection() {        Connection connection = null;        try {            connection = DriverManager.getConnection(url, user, password);        } catch (SQLException e) {            System.out.println("连接数据库失败");        }        return connection;    }    /** 关闭连接 */    public void closeConnection(Connection connection) {        try {            if(connection!=null)            connection.close();        } catch (SQLException e) {            e.printStackTrace();        }    }

使用Statement和preparetatement接口

例如添加内容到数据库

使用statement的为:

Connection connection=getConnection();//使用上面的getConnection();方法得到Connection的实例Statement statement = connection.createStatement();//的到statementString sql="insert intocourses(number,name)values(\"0006\",\"小明\")"statement.execute(sql);

使用prepareStatement

String sql="insert into courses (number,name) values(?,?)";Connection connection=getConnection();//使用上面的getConnection();方法得到Connection的实例PreparedStatement ps = connection.prepareStatement(sql);    ps.setString(1, "0009");    ps.setString(2, "麻子子");    ps.executeUpdate();        if (connection != null) {            System.out.println("添加成功");        }
0 0