You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java连接MS SQL Server插入数据至dbo.course表失败求助

问题排查与解决方案

嘿,我仔细看了你的Java代码,发现几个核心问题导致数据无法插入到dbo.course表,咱们一个个理清楚:

1. 最关键的疏漏:你从未执行INSERT语句!

你在代码里定义了sql变量存储插入语句,但从头到尾都没调用stmt.executeUpdate(sql)来让数据库执行这条语句。这就好比你写好了快递单,但没把快递交给快递员——数据库根本不知道你要插数据!

2. SQL语句的字符串拼接完全错误

你当前的SQL拼接代码是:

String sql = "INSERT INTO course (course_code, course_desc, course_chair)" + "VALUES ('\"+course_code+\"','\"+course_desc+\"','\"+course_chair+\"')";

这种写法会生成完全无效的SQL语句,最终的SQL会变成类似:

INSERT INTO course (course_code, course_desc, course_chair) VALUES ('"+course_code+"','"+course_desc+"','"+course_chair+"')

数据库会把"+course_code+"当成字符串内容,而不是你输入的变量值,自然插不进正确的数据。

3. 最优修复方案:改用PreparedStatement(安全又可靠)

直接拼接字符串不仅容易出错,还存在SQL注入风险,强烈建议使用PreparedStatement来处理插入操作,它能帮你自动处理参数转义和字符串拼接问题。

修正后的核心代码片段:

// 替换原来的stmt创建和SQL定义部分
String sql = "INSERT INTO course (course_code, course_desc, course_chair) VALUES (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
// 设置参数,索引从1开始
pstmt.setString(1, course_code);
pstmt.setString(2, course_desc);
pstmt.setString(3, course_chair);
// 执行插入语句,返回受影响的行数
int rowsAffected = pstmt.executeUpdate();
System.out.println("成功插入 " + rowsAffected + " 条数据!");

4. 额外优化:资源关闭的正确姿势

你当前的finally块里资源关闭顺序有误,应该先关闭Statement/PreparedStatement,再关闭Connection。更省心的是使用Java的try-with-resources语法,它会自动帮你关闭实现了AutoCloseable接口的资源,避免资源泄漏:

// 用try-with-resources包裹连接和PreparedStatement
try (Connection conn = DriverManager.getConnection(DB_URL);
     PreparedStatement pstmt = conn.prepareStatement(sql)) {
    // 这里执行参数设置和插入操作
} catch (SQLException se) {
    se.printStackTrace();
} catch(Exception e) {
    e.printStackTrace();
}

5. 可选排查点:事务提交设置

默认情况下JDBC连接是自动提交的,但如果你的数据库或连接配置了手动提交,执行插入后需要调用conn.commit()来提交事务。不过先解决前面的执行语句问题,这个可以作为后续排查的备选点。

完整修正后的代码参考:

import java.sql.*;
import java.util.*;

public class Main { // 类名建议首字母大写,符合Java规范
    static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    static final String DB_URL = "jdbc:sqlserver://localhost:1434;databaseName=database_sample;integratedSecurity=true";

    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        String course_code = null, course_desc = null, course_chair = null;

        try {
            // 注册JDBC驱动(JDBC 4.0+ 其实可以省略这一步,驱动会自动加载)
            Class.forName(JDBC_DRIVER);

            System.out.print("\nConnecting to database...");
            // 用try-with-resources自动管理连接和PreparedStatement
            try (Connection conn = DriverManager.getConnection(DB_URL)) {
                System.out.println(" SUCCESS!\n");

                // 获取用户输入
                System.out.print("Enter course code: ");
                course_code = scn.nextLine();
                System.out.print("Enter course description: ");
                course_desc = scn.nextLine();
                System.out.print("Enter course chair: ");
                course_chair = scn.nextLine();

                // 执行插入
                System.out.print("\nInserting records into table...");
                String sql = "INSERT INTO course (course_code, course_desc, course_chair) VALUES (?, ?, ?)";
                try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                    pstmt.setString(1, course_code);
                    pstmt.setString(2, course_desc);
                    pstmt.setString(3, course_chair);
                    int rowsAffected = pstmt.executeUpdate();
                    System.out.println(" SUCCESS! 插入了 " + rowsAffected + " 条数据\n");
                }
            }
        } catch(SQLException se) {
            se.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            scn.close(); // 别忘了关闭Scanner
        }
        System.out.println("Thank you for your patronage!");
    }
}

内容的提问来源于stack exchange,提问作者jgotnoswag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:28:46