标题: Backend - C# 操作PostgreSQL DB [打印本页] 作者: 莱莱 时间: 2024-9-3 19:36 标题: Backend - C# 操作PostgreSQL DB 目次
一、安装 Npgsql 插件
(一)作用
(二)操作
(三)注意
二、操作类
(一)操作类
1.NpgsqlConnection类
(1)作用
(2)引入
(3)数据库路由
(4)连接数据库
2.NpgsqlCommand类
(1)作用
(2)应用
(3)方法
① ExecuteNonQuery() 不返回任何效果。
② ExecuteScalar() 返回一个值。可搭配ExecuteScalar().ToString();输出值。
③ ExecuteReader() 返回一个IDataReader。
3.NpgsqlDataReader类
(1)作用
(2)应用
4.DataSet类
(1)作用
(2)应用
5.DataAdapter类:数据适配下令
(1)结合DataSet类,将数据可存储在DataSet对象中
(2)DataAdapter属性
(3)DataAdapter方法
(4)应用
(二)using
三、连接数据库
1. 简朴写法
2. 灵活写法
四、操作数据库
(一)创建&删除表
(二)插入
1. 单笔插入
(1)使用NpgsqlCommand
(2)使用BeginBinaryImport
① 定义时
② 调用时
2. 批量插入
(三)查询
(四)更新
1. 批量更新
五、写法
(一)字符串中的双引号
1. 用@符号+“”两个双引号
2. 用 \" 转义
六、问题
1. 问题:于 Npgsql.NpgsqlException 擲回破例狀況: 'mscorlib.dll'
2. 问题:42601: INSERT has more target columns than expressions 和 42601: syntax error at or near "[" 这两个问题
3. 问题:Binary importer closed in the middle of a row, cancelling import.
4. 问题:22P03: incorrect binary data format
5. 问题:Binary importer closed in the middle of a row, cancelling import.
6. 问题:error: Write for column 17 resolves to a different PostgreSQL type: OID 1114 than the first row resolved to (OID 0). Please make sure to use clr types that resolve to the same PostgreSQL type across rows. Alternatively pass the same NpgsqlDbType or DataTypeName to ensure the PostgreSQL type ends up to be identical.
7. 问题:The binary import operation was started with 23 column(s), but 24 value(s) were provided.
8. 问题: 22021: invalid byte sequence for encoding "UTF8": 0x00
9. 问题:Writing values of 'System.DateTimeOffset' is not supported for parameters having NpgsqlDbType 'Timestamp'.
10. 问题:Cannot write DateTimeOffset with Offset=08:00:00 to PostgreSQL type 'timestamp with time zone', only offset 0 (UTC) is supported.
11. 问题:error: Cannot write DateTime with Kind=Unspecified to PostgreSQL type 'timestamp with time zone', only UTC is supported. Note that it's not possible to mix DateTimes with different Kinds in an array, range, or multirange.
注意,这篇文章主要都是针对npgsql ,而不是sql。
一、安装 Npgsql 插件
解决:这个问题表达不明确,则自己写trycatch捕捉异常,并使用Console.ReadKey()让异常保留在exe控制台上查看。
2. 问题:42601: INSERT has more target columns than expressions 和 42601: syntax error at or near "[" 这两个问题
原因:批量添加时,不能使用[ ]或( )括号等来包裹批量记载,直接用逗号隔开每笔记载就好。
解决:取消外括号 ( )或[ ]
3. 问题:Binary importer closed in the middle of a row, cancelling import.
原因:要插入的列数和表格的列数不同等。
解决:列数和列值类型一定要对应。
4. 问题:22P03: incorrect binary data format
6. 问题:error: Write for column 17 resolves to a different PostgreSQL type: OID 1114 than the first row resolved to (OID 0). Please make sure to use clr types that resolve to the same PostgreSQL type across rows. Alternatively pass the same NpgsqlDbType or DataTypeName to ensure the PostgreSQL type ends up to be identical.
11. 问题:error: Cannot write DateTime with Kind=Unspecified to PostgreSQL type 'timestamp with time zone', only UTC is supported. Note that it's not possible to mix DateTimes with different Kinds in an array, range, or multirange.