SqlSugar operates MySQL database

SqlSugar operates MySQL database

C# operation DataTable sorting

In C#, we can use DataTableclasses to represent data tables in memory. DataTableThe class provides various methods and properties to manipulate the data table, including sorting.

To DataTablesort a class you can use DataViewa class. DataViewA class is an DataTableobject used for filtering and sorting. Here is a simple example showing how to DataTablesort a .

// 创建一个DataTable
DataTable dt = new DataTable();

// 添加列
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));

// 添加数据
dt.Rows.Add(1, "John", 25);
dt.Rows.Add(2, "Mary", 30);
dt.Rows.Add(3, "Tom", 22);
dt.Rows.Add(4, "Jack", 28);

// 创建DataView
DataView dv = new DataView(dt);

// 按Name列升序排序
dv.Sort = "Name ASC";

// 输出排序结果
foreach (DataRowView drv in dv)
{
    Console.WriteLine(drv["Id"] + "\\\\t" + drv["Name"] + "\\\\t" + drv["Age"]);
}

In the example above, we first created one DataTableand added some data to it. We then created one DataViewand sorted by column ascending using Sortthe property . NameFinally, we use foreacha loop to traverse DataViewand output the sorted results.

In addition to sorting by a single column, you can also sort by multiple columns. For example, to sort by Namea column in ascending order and then in Agedescending order, you can use the following code:

// 按Name列升序,按Age列降序排序
dv.Sort = "Name ASC, Age DESC";

In actual development, we often need to sort data. Data sorting functionality can be easily implemented using DataTableand .DataView

SQLSugar connects to MySQL database connection string configuration

Before using SQLSugar to connect to the MySQL database, we need to configure the connection string first. The following is the format of a MySQL connection string:

Server=服务器地址;Database=数据库名称;Uid=用户名;Pwd=密码;Charset=utf8;

Among them, the meaning of each parameter is as follows:

  • Server: MySQL server address.
  • Database: The name of the database to connect to.
  • Uid: The username to connect to the MySQL server.
  • Pwd: Password to connect to the MySQL server.
  • Charset: The character set used when connecting to the MySQL server, the default is utf8.

The following is an example connection string:

string connectionString = "Server=localhost;Database=mydatabase;Uid=myusername;Pwd=mypassword;Charset=utf8;";

In SQLSugar, we can use the following code to connect to the MySQL database:

using SqlSugar;

// 创建数据库连接对象
var db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = connectionString, // 连接字符串
    DbType = DbType.MySql, // 数据库类型
    IsAutoCloseConnection = true, // 自动关闭连接
    InitKeyType = InitKeyType.Attribute // 初始化主键和自增列信息
});

In the above code, ConnectionStringthe attribute is used to set the connection string, DbTypethe attribute is used to set the database type, IsAutoCloseConnectionthe attribute is used to set whether to automatically close the connection, and InitKeyTypethe attribute is used to set the way of initializing the primary key and auto-incrementing column information. For the meaning of these attributes, please refer to the official SQLSugar documentation.

In actual development, we can modify the parameters of the connection string as needed to meet different needs.

SqlSugar MySQL executes BulkCopy and reports an error denying access

When using BulkCopythe method of SqlSugar to insert data into the MySQL database in batches, sometimes the following errors are encountered:

System.UnauthorizedAccessException: Access to the path 'C:\\\\Windows\\\\TEMP\\\\*.tmp' is denied.

This is because BulkCopymethods write data to temporary files when executed, and these files are stored in C:\\\\Windows\\\\TEMPdirectories by default. If the current user does not have permission to access the directory, the above error will occur.

To solve this problem, you can specify where the temporary files are stored by modifying the properties MySqlBulkLoaderof the class . LocalInfileHandlerHere is an example:

using MySql.Data.MySqlClient;

// 创建MySQL连接对象
var conn = new MySqlConnection(connectionString);

// 打开连接
conn.Open();

// 创建BulkCopy实例
var bulkCopy = new MySqlBulkCopy(conn);

// 指定临时文件存储位置
bulkCopy.LocalInfileHandler = new MySqlLocalInfileFileStream(@"D:\\\\Temp");

// 将数据写入数据库
bulkCopy.WriteToServer(dataTable);

// 关闭连接
conn.Close();

In the above example, we first created an MySqlConnectionobject and opened the connection. Then, we create an MySqlBulkCopyinstance and use MySqlLocalInfileFileStreamthe class to specify where the temporary files are stored D:\\\\Temp. Finally, we use WriteToServerthe method to write the data to the database and then close the connection.

Through the above methods, we can solve BulkCopythe access denial problem in MySQL.

To perform operations in a MySQL database INSERT, you can use the methods SQLSugarprovided Insertable. The following is an example showing how to Insertableinsert data into a MySQL database using the method:

using SqlSugar;

// 创建数据库连接对象
var db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = connectionString, // 连接字符串
    DbType = DbType.MySql, // 数据库类型
    IsAutoCloseConnection = true, // 自动关闭连接
    InitKeyType = InitKeyType.Attribute // 初始化主键和自增列信息
});

// 创建待插入数据
var data = new YourDataClass()
{
    // 填充数据
};

// 插入数据
db.Insertable(data).ExecuteCommand();

In the above code, we first created an SqlSugarClientobject and ConnectionStringset the connection string using properties. Then, we create a data object to be inserted dataand pass it to Insertablethe method. Finally, we use ExecuteCommandthe method to perform the insert operation.

In Insertableaddition to methods, SQLSugarmany other methods are provided, such as InsertRange, , InsertReturnIdentityetc., for performing different types of INSERToperations. For details about these methods, please refer to SQLSugarthe official documentation.

In actual development, we can choose a suitable method according to our needs to implement operations such as data insertion and update.

To perform operations in a MySQL database INSERT, you can use the methods SQLSugarprovided Insertable. The following is an example showing how to Insertableinsert data into a MySQL database using the method:

using SqlSugar;

// 创建数据库连接对象
var db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = connectionString, // 连接字符串
    DbType = DbType.MySql, // 数据库类型
    IsAutoCloseConnection = true, // 自动关闭连接
    InitKeyType = InitKeyType.Attribute // 初始化主键和自增列信息
});

// 创建待插入数据
var data = new YourDataClass()
{
    // 填充数据
};

// 插入数据
db.Insertable(data).ExecuteCommand();

In the above code, we first created an SqlSugarClientobject and ConnectionStringset the connection string using properties. Then, we create a data object to be inserted dataand pass it to Insertablethe method. Finally, we use ExecuteCommandthe method to perform the insert operation.

In Insertableaddition to methods, SQLSugarmany other methods are provided, such as InsertRange, , InsertReturnIdentityetc., for performing different types of INSERToperations. For details about these methods, please refer to SQLSugarthe official documentation.

In actual development, we can choose a suitable method according to our needs to implement operations such as data insertion and update.

INSERTTo perform operations in the MySQL database , native SQL statements can be executed using the SQLSugarprovided objects. AdoFollowing is an example showing how to use Adoobjects to insert data into a MySQL database:

using SqlSugar;

// 创建数据库连接对象
var db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = connectionString, // 连接字符串
    DbType = DbType.MySql, // 数据库类型
    IsAutoCloseConnection = true, // 自动关闭连接
    InitKeyType = InitKeyType.Attribute // 初始化主键和自增列信息
});

// 创建待插入数据
var data = new YourDataClass()
{
    // 填充数据
};

// 执行插入操作
db.Ado.ExecuteCommand("INSERT INTO your_table (column1, column2) VALUES (@column1, @column2)",
    new { column1 = data.Column1, column2 = data.Column2 });

In the above code, we SqlSugarClientcreated a database connection object to connect to MySQL using the object. Then, we create a data object to be inserted data, and use Adothe object's ExecuteCommandmethods to execute native SQL statements. In SQL statements, we use VALUESclauses to specify the values ​​to be inserted and @column1and @column2placeholders to refer to properties of data objects. Finally, we replace the placeholders with the actual values ​​of the data object via the anonymous object.

In addition to INSERToperations, Adoobjects can also be used to execute various types of SQL statements, including SELECT, , UPDATEand DELETE, etc. Using Adoobjects can take advantage of the powerful functions of native SQL statements to achieve more flexible data operations.

In actual development, we can choose a suitable method according to our needs to implement operations such as data insertion and update.

When using SQLSugarto connect to the MySQL database, if you execute Topthe syntax, you may encounter the following error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 10' at line 1.

This is due to the fact that the MySQL database does not support Topthe syntax, which should be used instead LIMIT. To fix this, you can use the SQLSugarprovided ASgrammar, which Topconverts the grammar to LIMITa grammar. Here is an example:

using SqlSugar;

// 创建数据库连接对象
var db = new SqlSugarClient(new ConnectionConfig()
{
    ConnectionString = connectionString, // 连接字符串
    DbType = DbType.MySql, // 数据库类型
    IsAutoCloseConnection = true, // 自动关闭连接
    InitKeyType = InitKeyType.Attribute // 初始化主键和自增列信息
});

// 查询前10条数据
var list = db.Queryable<YourDataClass>()
             .AS("t")
             .OrderBy("column")
             .Take(10)
             .ToList();

In the above code, we use ASgrammar to Topconvert grammar to LIMITgrammar. Specifically, we use ASthe method to set the alias of the data table YourDataClassto t, and use Takethe method to specify the number of records to be queried. Finally, we use ToListthe method to get the query results.

Through the above method, we can execute the syntax in the MySQL database Topto fetch the specified number of records. It should be noted that ASthe method can only be used for query operations, not insert, update and delete operations.

Guess you like

Origin blog.csdn.net/Documentlv/article/details/130429763