mysql数据库url怎么写 mysql数据库怎么插入数据

mysql数据库url怎么写 mysql数据库怎么插入数据
最新回答
や泪漫延街

2020-07-01 13:55:34

MySQL数据库URL编写MySQL数据库URL的标准格式为:

jdbc:mysql://[hostname]:[port]/[database name]
  • hostname:MySQL服务器地址(如localhost或IP地址192.168.1.100)。
  • port:MySQL服务端口(默认3306,可省略)。
  • database name:要连接的数据库名称(如mydb)。

示例

  • 连接本地默认端口的mydb数据库:jdbc:mysql://localhost:3306/mydb
  • 连接远程服务器(IP为203.0.113.5,端口3307)的testdb数据库:jdbc:mysql://203.0.113.5:3307/testdb

MySQL数据库数据插入(Java JDBC示例)向如弯MySQL插入数据需遵循以下步骤:

  1. 加拦誉载JDBC驱动

    Class.forName("com.mysql.cj.jdbc.Driver");
  2. 建立数据简橡段库连接

    String jdbcUrl = "jdbc:mysql://localhost:3306/mydb";String username = "root";String password = "123456";Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
  3. 创建PreparedStatement

    String sql = "INSERT INTO users (name, age) VALUES (?, ?)";PreparedStatement statement = connection.prepareStatement(sql);
  4. 设置参数并执行插入

    statement.setString(1, "Alice"); // 第一个问号替换为字符串statement.setInt(2, 25); // 第二个问号替换为整数int affectedRows = statement.executeUpdate(); // 返回受影响的行数
  5. 关闭资源

    statement.close();connection.close();

完整代码示例

import java.sql.*;public class InsertData { public static void main(String[] args) { try { // 1. 加载驱动 Class.forName("com.mysql.cj.jdbc.Driver"); // 2. 建立连接 String url = "jdbc:mysql://localhost:3306/mydb"; Connection conn = DriverManager.getConnection(url, "root", "password"); // 3. 准备SQL并设置参数 String sql = "INSERT INTO employees (id, name) VALUES (?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 101); pstmt.setString(2, "John Doe"); // 4. 执行插入 int rows = pstmt.executeUpdate(); System.out.println("插入了 " + rows + " 行数据"); // 5. 关闭资源 pstmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } }}

注意事项

  • 使用try-with-resources可自动关闭资源(Java 7+)。
  • 参数化查询(PreparedStatement)可防止SQL注入。
  • 捕获SQLException处理数据库错误。