sqlsugar插入
时间: 2024-05-24 22:08:29 浏览: 19
SqlSugar 是一款ORM(Object Relational Mapping)框架,提供了丰富的API,使得开发者可以通过简单的操作来进行数据库的访问和操作。下面是 SqlSugar 插入数据的介绍:
1. 新建一个实体对象
```
var user = new User()
{
Name = "John",
Age = 25,
Gender = "Male"
};
```
2. 获取 SqlSugar 对象
```
var db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "yourConnectionString",
DbType = DbType.SqlServer, // 数据库类型
IsAutoCloseConnection = true // 是否自动关闭连接
});
```
3. 插入数据
```
db.Insertable(user).ExecuteCommand();
```
`Insertable` 方法用于创建一个插入对象,参数为需要插入的实体对象;`ExecuteCommand` 方法则用于执行插入操作。
相关问题
sqlsugar 插入指定表
在使用 SqlSugar 进行插入数据时,需要先实例化一个 SugarClient 对象,具体代码如下:
```csharp
// 连接字符串
string connectionString = "server=localhost;database=test;uid=root;pwd=123456";
// 实例化 SugarClient 对象
var db = new SqlSugar.SugarClient(connectionString);
```
接着,使用 Insertable 方法指定要插入的表名,代码如下:
```csharp
// 指定要插入的表名
var insertable = db.Insertable(new { Name = "张三", Age = 20 }).IntoTable("user");
```
在上述代码中,我们通过匿名对象指定要插入的数据,然后使用 IntoTable 方法指定要插入的表名为 user。
接下来,我们可以继续链式调用其他插入操作,比如插入多条数据:
```csharp
var list = new List<object>
{
new { Name = "张三", Age = 20 },
new { Name = "李四", Age = 21 }
};
// 插入多条数据
var insertable = db.Insertable(list).IntoTable("user");
```
或者插入一条数据并返回自增主键:
```csharp
// 插入一条数据并返回自增主键
var id = db.Insertable(new { Name = "张三", Age = 20 }).IntoTable("user").ExecuteReturnIdentity();
```
最后,我们调用 ExecuteCommand 方法执行插入操作:
```csharp
// 执行插入操作
var result = insertable.ExecuteCommand();
```
其中,ExecuteCommand 方法返回插入操作影响的行数。
sqlsugar插入空时间为1990
SQLSugar 在插入空时间时默认会将其转换为 `1990-01-01 00:00:00`,这是因为在 SQL Server 中,日期时间列默认值为 `1900-01-01 00:00:00.000`,而在 SQLSugar 中,空日期时间被视为默认值。如果你想要插入一个空时间,请使用 `null` 值进行插入,例如:
```c#
var data = new DemoTable()
{
Id = 1,
Name = "test",
CreateTime = null
};
db.Insertable(data).ExecuteCommand();
```
这样就可以插入一个空时间了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)