SQLite中替代DataTable.Load()的方案:解决NotSupportedException异常
解决SqliteDataReader加载DataTable时的NotSupportedException问题
嘿,这个问题我熟!不少SQLite的DataReader实现(尤其是Microsoft.Data.Sqlite)确实不支持DataTable.Load()方法,一调用就抛NotSupportedException。给你两个靠谱的替代方案,亲测有效:
方案1:手动构建DataTable(兼容性拉满)
这个方法完全绕开Load(),自己控制列和行的创建,不管哪个版本的SQLite库都能用:
DataTable dataTable = new DataTable(); using (SqliteDataReader reader = command.ExecuteReader()) { // 先根据Reader的字段信息创建DataTable的列 for (int i = 0; i < reader.FieldCount; i++) { string columnName = reader.GetName(i); Type columnType = reader.GetFieldType(i); dataTable.Columns.Add(columnName, columnType); } // 逐行读取数据并添加到DataTable while (reader.Read()) { DataRow newRow = dataTable.NewRow(); for (int i = 0; i < reader.FieldCount; i++) { // 处理DBNull的情况,避免赋值出错 newRow[i] = reader.IsDBNull(i) ? DBNull.Value : reader[i]; } dataTable.Rows.Add(newRow); } }
小贴士:一定要用using包裹SqliteDataReader,确保资源及时释放;处理DBNull很关键,不然遇到空值会抛出异常。
方案2:使用SqliteDataAdapter(代码更简洁)
如果你的项目依赖的SQLite库支持SqliteDataAdapter(比如System.Data.SQLite或较新的Microsoft.Data.Sqlite),这个方法更省心,一行填充搞定:
DataTable dataTable = new DataTable(); using (SqliteDataAdapter adapter = new SqliteDataAdapter(command)) { adapter.Fill(dataTable); }
SqliteDataAdapter.Fill()底层会自动处理列的创建和行的填充,不需要你手动写循环,代码干净很多。
内容的提问来源于stack exchange,提问作者G.Dealmeida
相关产品推荐
相关产品推荐

