java(连接mysql)

连接数据库的方法:

//方式一
    public void connect01() throws Exception{
        Driver driver = new Driver();//创建driver对象
        String url = "jdbc:mysql://localhost:3306/data";
        //将用户和密码放入到Properties对象
        Properties properties = new Properties();
        properties.setProperty("user","root");//用户
        //properties.setProperty("password","123456");//密码
        Connection connect = driver.connect(url, properties);//得到连接
    }
    public void connect02() throws Exception{
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");//使用反射加载Driver类
        Driver driver = (Driver) aClass.newInstance();
    }
    public void connect03() throws Exception{
        //使用Class.forName自动完成注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/data";
        String user = "root";
        //String password = "123456";
        Connection connection = DriverManager.getConnection(url, user, password);
    }
    public void connect04() throws Exception{
        //在3的基础上改进,增加配置文件,让连接mysql更加灵活
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\jdbc_\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        System.out.println(connection);
    }

ResultSet基本介绍:

1.表示数据库结果集的数据表,通常通过执行查询数据库的语句生成

2.ResultSet对象保持一个光标指向其当前的数据行。最开始光标位于第一行之前

3.next方法将光标移动到下一行,并且由于在ResultSet对象中没有更多行时返回false,因此可以在while循环中使用循环来遍历结果集

Statement statement = connection.createStatement();
        String sql = "select id,name,sex,borndate from actor";
        ResultSet resultSet = statement.executeQuery(sql);//得到结果集
        while (resultSet.next()){
            int id = resultSet.getInt(1);//获取该行第一列
            String name = resultSet.getString(2);//第二列
            String sex = resultSet.getString(3);
            Date date = resultSet.getDate(4);
            System.out.println(id + "\t" + name + "\t" + sex + "\t" + date);
        }

Statement基本介绍:

1.Statement对象用于执行静态SQL语句并返回其生成的结果的对象

2.在连接建立后,需要对数据库进行访问,执行命令或是SQL语句,可以通过

        Statement [ 存在SQL注入 ]

        PreparedStatement [ 预处理 ]

        CallableStatement [ 存储过程 ]

3.Statement对象执行SQL语句,存在SQL注入风险

4.SQL注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句段或命令,恶意攻击数据库

5.要防范SQL注入,只要用PreparedStatement(从Statement扩展而来)取代Statement就可以

public class preparedStatement {
    public static void main(String[] args) throws Exception{
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\jdbc_\\mysql.properties"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        //String sql = "create table admin( id int,name varchar(32))";
        String sql = "insert into admin values(?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,1);
        preparedStatement.setString(2,"jack");
        preparedStatement.executeUpdate();
        preparedStatement.close();
        connection.close();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java连接MySQL通常涉及到Java开发框架和数据库驱动程序的使用。主要步骤包括下载并配置MySQL JDBC (Java Database Connectivity) 驱动,然后在Java代码中建立到MySQL服务器的连接。 ### 步骤详解: #### 1. 下载并安装MySQL JDBCDriver 访问MySQL官网的Driver下载页面,选择适合您系统版本的JDBC驱动(例如,`mysql-connector-java-x.x.xx.jar`),下载并将其放置在项目的lib目录下。 #### 2. 配置环境变量 确保已经将MySQL服务器路径添加到系统的PATH环境变量中,并设置好MySQL服务器的配置文件my.cnf中的`character-set-server=utf8mb4`等参数,保证数据传输的兼容性和效率。 #### 3. 创建连接Java代码中创建数据库连接,首先需要导入必要的包: ```java import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; ``` 接下来编写获取数据库连接的代码: ```java public Connection getConnection() { String url = "jdbc:mysql://localhost:3306/database_name"; String user = "username"; String password = "password"; try { Class.forName("com.mysql.cj.jdbc.Driver"); return DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException | SQLException e) { throw new RuntimeException(e); } } ``` 这里的URL指定了服务器地址、端口、数据库名;用户和密码则对应于数据库的身份验证信息。 #### 4. 使用连接 一旦成功建立连接,就可以利用Connection对象执行SQL查询、插入、更新或删除操作了。示例如下: ```java public void executeQuery(String sql) throws SQLException { Connection conn = null; PreparedStatement pstmt = null; try { conn = getConnection(); pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); // 或者用于查询的结果集,如pstmt.executeQuery() System.out.println("Query executed successfully."); } finally { if (pstmt != null) { pstmt.close(); } if (conn != null) { conn.close(); } } } ``` #### 相关问题: 1. **如何处理Java连接MySQL时遇到的常见错误**? 这些错误可能包括但不限于无效的数据库连接、找不到驱动等问题。 2. **在大型项目中如何优化Java连接MySQL的性能**? 包括但不限于使用连接池技术、事务管理策略等。 3. **在使用Java连接MySQL时,如何处理安全性和权限认证的问题**? 包括SSL加密、用户角色授权等方面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值