SqlParameter.Value = NULL 引发的数据库异常

本文介绍在.NET框架下使用SqlCommand向数据库存储过程传递参数时,如何正确处理null值的问题。当参数值为null时,应使用DBNull.Value替代null,以避免出现异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = new SqlConnection(@"Data Source=PC201305032338\SQLEXPRESS;Initial Catalog=DBTest;Integrated Security=True"); ;
            cmd.Connection.Open();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "CheckDBNull";
            SqlParameter p1 = new SqlParameter();
            p1.ParameterName = "@p1";
            p1.DbType = DbType.String;
            p1.Value = null;
            cmd.Parameters.Add(p1);

            string rslt = cmd.ExecuteScalar().ToString();
        }

运行以上代码,将抛出“过程或函数 'CheckDBNull' 需要参数 '@p1',但未提供该参数。”的异常,问题就出在 p1.Value = null 这句话,这个null可能是某个对象的属性,但只要为null都是会抛出以上异常的。

[原因]

.Net框架规定:IDataParameter在向服务器发送 null 参数值时,用户必须指定 DBNull,而不是 null。系统中的 null 值是一个没有值的空对象。DBNull 用于表示 null 值。

[解决]

 在给SqlParameter赋值时,如果参数值为null,将参数赋值为DBNull.Value,如:p1.Value = DBNull.Value

[参考]

IDataParameter接口,SqlParameter类实现该接口:public sealed class SqlParameter : DbParameter, IDbDataParameter, IDataParameter, ICloneable

DBNull和Null的区别,Null是.net中无效的对象引用;DBNull是一个类,DBNull.Value是它唯一的实例,它指数据库中数据为空(<NULL>)时,在.net中的值。

转载于:https://www.cnblogs.com/ccweb/p/3403492.html

using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Configuration; namespace DBUtility { public class DbHelperSQL { // Fields public static string connectionString; // Methods static DbHelperSQL() { connectionString = ConfigurationManager.AppSettings["ConnectionString"]; } public DbHelperSQL() { } private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); return command; } private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = new SqlCommand(storedProcName, connection); command.CommandType = CommandType.StoredProcedure; foreach (SqlParameter parameter in parameters) { if (parameter != null) { if (((parameter.Direction == ParameterDirection.InputOutput) || (parameter.Direction == ParameterDirection.Input)) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } command.Parameters.Add(parameter); } } return command; } public static SqlDataReader ExecuteReader(string strSQL) { SqlDataReader dr; SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(strSQL, connection); try { connection.Open(); dr= cmd.ExecuteReader(); } catch (SqlException e) { throw new Exception(e.Message); } return dr; } public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms) { SqlDataReader dr; SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); SqlDataReader myReader = cmd.ExecuteReader(); cmd.Parameters.Clear(); dr = myReader; } catch (SqlException e) { throw new Exception(e.Message); } return dr; } public static int ExecuteSql(string SQLString) { int count; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); return cmd.ExecuteNonQuery(); } catch (SqlException E) { connection.Close(); throw new Exception(E.Message); } } } return count; } public static int ExecuteSql(string SQLString, string content) { int count; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); SqlParameter myParameter = new SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); count = cmd.ExecuteNonQuery(); } catch (SqlException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } return count; } public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms) { int count; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (SqlException E) { throw new Exception(E.Message); } } } return count; } public static int ExecuteSqlByTime(string SQLString, int Times) { int count; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; return cmd.ExecuteNonQuery(); } catch (SqlException E) { connection.Close(); throw new Exception(E.Message); } } } return count; } public static object ExecuteSqlGet(string SQLString, string content) { object esg; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); SqlParameter myParameter = new SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); object obj = cmd.ExecuteScalar(); if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) { return null; } esg = obj; } catch (SqlException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } return esg; } public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) { int count; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(strSQL, connection); SqlParameter myParameter = new SqlParameter("@fs", SqlDbType.Image); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); count = cmd.ExecuteNonQuery(); } catch (SqlException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } return count; } public static void ExecuteSqlTran(ArrayList SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n].ToString(); if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; cmd.ExecuteNonQuery(); } } tx.Commit(); } catch (SqlException E) { tx.Rollback(); throw new Exception(E.Message); } } } public static void ExecuteSqlTran(Hashtable SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); trans.Commit(); } } catch { trans.Rollback(); throw; } } } } public static bool Exists(string strSql) { int cmdresult; object obj = GetSingle(strSql); if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } return true; } public static bool Exists(string strSql, params SqlParameter[] cmdParms) { int cmdresult; object obj = GetSingle(strSql, cmdParms); if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } return true; } public static int GetMaxID(string FieldName, string TableName) { object obj = GetSingle("select max(" + FieldName + ")+1 from " + TableName); if (obj == null) { return 1; } return int.Parse(obj.ToString()); } public static object GetSingle(string SQLString) { object gs; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) { return null; } return obj; } catch (SqlException e) { connection.Close(); throw new Exception(e.Message); } } } return gs; } public static object GetSingle(string SQLString, params SqlParameter[] cmdParms) { object gs; using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) { return null; } return obj; } catch (SqlException e) { throw new Exception(e.Message); } } } return gs; } private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms) { if (conn.State != ConnectionState.Open) { conn.Open(); } cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) { cmd.Transaction = trans; } cmd.CommandType = CommandType.Text; if (cmdParms != null) { foreach (SqlParameter parameter in cmdParms) { if (((parameter.Direction == ParameterDirection.InputOutput) || (parameter.Direction == ParameterDirection.Input)) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } } public static DataSet Query(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); new SqlDataAdapter(SQLString, connection).Fill(ds, "ds"); } catch (SqlException ex) { throw new Exception(ex.Message); } return ds; } } public static DataSet Query(string SQLString,int pageindx,int pagesize,string tablename) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); new SqlDataAdapter(SQLString, connection).Fill(ds,pageindx,pagesize,tablename); } catch (SqlException ex) { throw new Exception(ex.Message); } return ds; } } public static DataSet Query(string SQLString, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.SelectCommand.CommandTimeout = Times; command.Fill(ds, "ds"); } catch (SqlException ex) { throw new Exception(ex.Message); } return ds; } } public static DataSet Query(string SQLString, params SqlParameter[] cmdParms) { DataSet dsq; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (SqlException ex) { throw new Exception(ex.Message); } dsq = ds; } } return dsq; } public static DataSet Query(string SQLString,string tablename) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); new SqlDataAdapter(SQLString, connection).Fill(ds, tablename); } catch (SqlException ex) { throw new Exception(ex.Message); } return ds; } } public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters) { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.CommandType = CommandType.StoredProcedure; return command.ExecuteReader(); } public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = BuildIntCommand(connection, storedProcName, parameters); rowsAffected = command.ExecuteNonQuery(); int result = (int)command.Parameters["ReturnValue"].Value; connection.Close(); return result; } } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.SelectCommand.CommandTimeout = Times; sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } public static void RunStatProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = BuildIntCommand(connection, storedProcName, parameters); rowsAffected = command.ExecuteNonQuery(); connection.Close(); } } } }
最新发布
07-25
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace _2 { public partial class 讨论区添加 : Form { // 添加_imageData字段定义 private byte[] _imageData = null; public 讨论区添加() { InitializeComponent(); } private void pabtn_Click(object sender, EventArgs e) { // 验证输入 if (string.IsNullOrWhiteSpace(论坛名字.Text) || string.IsNullOrWhiteSpace(发表内容.Text)) { MessageBox.Show("论坛名称和内容不能为空", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } using (Dao4 dao = new Dao4()) { dao.Connect(); // 确保连接已打开 // 修正SQL语句 - 添加表名和字段名 string sql = @" INSERT INTO T_Say (Content, Image, Lname) VALUES (@Content, @Image, @Lname)"; // 创建参数列表 List<SqlParameter> parameters = new List<SqlParameter> { // 内容参数 new SqlParameter("@Content", SqlDbType.NVarChar) { Value = 发表内容.Text }, // 图片参数 new SqlParameter("@Image", SqlDbType.VarBinary) { Value = _imageData ?? (object)DBNull.Value }, // 论坛名称参数 new SqlParameter("@Lname", SqlDbType.NVarChar) { Value = 论坛名字.Text } }; // 执行SQL命令 try { int n = dao.ExecuteParameterized(sql, parameters); if (n > 0) { MessageBox.Show("添加成功"); this.Close(); // 关闭窗口 } else { MessageBox.Show("添加失败"); } } catch (SqlException ex) { MessageBox.Show($"数据库错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void lblImageStatus_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void 发表内容_TextChanged(object sender, EventArgs e) { } private void pc_Click(object sender, EventArgs e) { } private void 论坛名字_TextChanged(object sender, EventArgs e) { } private void p_Click(object sender, EventArgs e) { } private void pcbtn_Click(object sender, EventArgs e) { } private void btnSelectImage_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp"; openFileDialog.Title = "选择图片"; if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; try { // 检查文件是否存在 if (!File.Exists(filePath)) { MessageBox.Show($"文件不存在: {filePath}"); return; } // 检查文件大小限制(例如 2MB) FileInfo fileInfo = new FileInfo(filePath); if (fileInfo.Length > 2 * 1024 * 1024) // 2MB { MessageBox.Show("图片大小不能超过 2MB"); return; } // 读取图片文件为字节数组 _imageData = File.ReadAllBytes(filePath); // 在PictureBox中显示图片 using (MemoryStream ms = new MemoryStream(_imageData)) { pictureBox1.Image = Image.FromStream(ms); } lblImageStatus.Text = $"已选择图片 ({fileInfo.Length / 1024} KB)"; } catch (Exception ex) { MessageBox.Show($"加载图片失败: {ex.Message}"); _imageData = null; pictureBox1.Image = null; lblImageStatus.Text = "未选择图片"; } } } } private void pictureBox1_Click(object sender, EventArgs e) { } } } 怎么改
07-05
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace _2 { public partial class 讨论区添加 : Form { public 讨论区添加() { InitializeComponent(); } private void pabtn_Click(object sender, EventArgs e) { // 如果文本框内容为空,返回 if (论坛名字.Text.Trim() == "" || 发表内容.Text.Trim() == "" ) { MessageBox.Show("有空项", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (string.IsNullOrWhiteSpace(论坛名字.Text)) { MessageBox.Show("Pname不能为空"); return; } Dao4 dao = new Dao4(); dao.Connect(); // 确保连接已打开 // 使用参数化查询并指定实际字段名 string sql = @" INSERT INTO (Content,Image,Lname) VALUES (@Content, @Image, @Lname)"; // 创建参数列表,使用实际字段名作为参数名 List<SqlParameter> parameters = new List<SqlParameter> { // Pname - 文本类型 new SqlParameter("@Content", SqlDbType.NVarChar) { Value = 发表内容.Text }, // Stype - 文本类型 new SqlParameter("@Content", SqlDbType.NVarChar) { Value = 论坛名字.Text }, // 添加图片参数 new SqlParameter("@Image", SqlDbType.VarBinary) { Value = _imageData ?? (object)DBNull.Value }, }; // 执行SQL命令 int n = dao.ExecuteParameterized(sql, parameters); if (n > 0) { MessageBox.Show("添加成功"); this.Close(); // 添加这行代码关闭窗口 } else { MessageBox.Show("添加失败"); } } private void lblImageStatus_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void 发表内容_TextChanged(object sender, EventArgs e) { } private void pc_Click(object sender, EventArgs e) { } private void 论坛名字_TextChanged(object sender, EventArgs e) { } private void p_Click(object sender, EventArgs e) { } private void pcbtn_Click(object sender, EventArgs e) { } private void btnSelectImage_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp"; openFileDialog.Title = "选择图片"; if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; try { // 检查文件是否存在 if (!File.Exists(filePath)) { MessageBox.Show($"文件不存在: {filePath}"); return; } // 检查文件大小限制(例如 2MB) FileInfo fileInfo = new FileInfo(filePath); if (fileInfo.Length > 2 * 1024 * 1024) // 2MB { MessageBox.Show("图片大小不能超过 2MB"); return; } // 读取图片文件为字节数组 _imageData = File.ReadAllBytes(filePath); // 在PictureBox中显示图片 - 使用内存流避免文件锁定 using (MemoryStream ms = new MemoryStream(_imageData)) { pictureBox1.Image = Image.FromStream(ms); } lblImageStatus.Text = $"已选择图片 ({fileInfo.Length / 1024} KB)"; } catch (FileNotFoundException ex) { MessageBox.Show($"文件不存在: {ex.FileName}"); _imageData = null; } catch (PathTooLongException) { MessageBox.Show("文件路径过长,请将文件移动到较短的路径下"); _imageData = null; } catch (UnauthorizedAccessException) { MessageBox.Show("没有权限访问该文件"); _imageData = null; } catch (IOException ex) { MessageBox.Show($"文件读取错误: {ex.Message}"); _imageData = null; } catch (Exception ex) { MessageBox.Show($"加载图片失败: {ex.Message}"); _imageData = null; } finally { // 如果读取失败,清除图片预览 if (_imageData == null) { pictureBox1.Image = null; lblImageStatus.Text = "未选择图片"; } } } } } private void pictureBox1_Click(object sender, EventArgs e) { } } } 怎么修改报错:不存在_imageData
07-05
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace _2 { public partial class Addnotepoint : Form { // 存储图片的字节数组 private byte[] _imageData = null; public Addnotepoint() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void Addnotepoint_Load(object sender, EventArgs e) { } private void textBox4_TextChanged(object sender, EventArgs e) { } private void label3_Click(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void label4_Click(object sender, EventArgs e) { } private void pcbtn_Click(object sender, EventArgs e) { this.Close(); } private void pabtn_Click(object sender, EventArgs e) { //如果文本框内容为空,返回 if(textBox1.Text.Trim() == "" || textBox2.Text.Trim() == ""|| textBox4.Text.Trim() == "" || richTextBox1.Text.Trim() == ""|| dateTimePicker1.Text =="") { MessageBox.Show("有空项", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // 在插入前添加输入验证 if (string.IsNullOrWhiteSpace(textBox1.Text) || !int.TryParse(textBox1.Text, out _)) { MessageBox.Show("PID必须为有效整数"); return; } if (string.IsNullOrWhiteSpace(textBox2.Text)) { MessageBox.Show("Pname不能为空"); return; } if (dateTimePicker1.Value > DateTime.Now) { MessageBox.Show("保存日期不能是未来时间"); return; } Dao2 dao = new Dao2(); dao.Connect(); // 确保连接已打开 // 使用参数化查询并指定实际字段名 string sql = @" INSERT INTO T_Point (Pid, Pname, Stype, [Content], Savedate, Image) VALUES (@Pid, @Pname, @Stype, @Content, @Savedate, @Image)"; // 创建参数列表,使用实际字段名作为参数名 List<SqlParameter> parameters = new List<SqlParameter> { // Pid - 假设是整数类型 new SqlParameter("@Pid", SqlDbType.Int) { Value = int.Parse(textBox1.Text) }, // Pname - 文本类型 new SqlParameter("@Pname", SqlDbType.NVarChar) { Value = textBox2.Text }, // Stype - 文本类型 new SqlParameter("@Stype", SqlDbType.NVarChar) { Value = textBox4.Text }, // [Content] - 注意Content是SQL关键字,需要用方括号包裹 new SqlParameter("@Content", SqlDbType.NVarChar) { Value = richTextBox1.Text }, // Savedate - 日期类型 new SqlParameter("@Savedate", SqlDbType.DateTime) { Value = dateTimePicker1.Value }, // 添加图片参数 new SqlParameter("@Image", SqlDbType.VarBinary) { Value = _imageData ?? (object)DBNull.Value } }; // 执行SQL命令 int n = dao.ExecuteParameterized(sql, parameters); if (n > 0) { MessageBox.Show("添加成功"); this.Close(); // 添加这行代码关闭窗口 } else { MessageBox.Show("添加失败"); } } private void textBox2_TextChanged(object sender, EventArgs e) { } private void richTextBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp"; openFileDialog.Title = "选择图片"; if (openFileDialog.ShowDialog() == DialogResult.OK) { try { string filePath = openFileDialog.FileName; // 读取图片文件为字节数组 _imageData = File.ReadAllBytes(filePath); // 在PictureBox中显示图片 pictureBox1.Image = Image.FromFile(filePath); lblImageStatus.Text = "已选择图片"; } catch (Exception ex) { MessageBox.Show($"加载图片失败: {ex.Message}"); _imageData = null; } } } } private void lblImageStatus_Click(object sender, EventArgs e) { } } } 报错:_imageData = File.ReadAllBytes(filePath);File不存在
07-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值