c#控制台应用程序在MySQL数据库中插入行
本文关键字:插入 数据库 MySQL 控制台 应用程序 | 更新日期: 2023-09-27 18:04:45
我有一个控制台应用程序(在Visual Studio 2013 Ultimate),我想在我的数据库中插入数据。
我需要如何在这个应用程序中连接和插入数据?
我的数据库的查询是:INSERT INTO test.user (id, name) VALUES (NULL, 'Some name');
我现在的代码是:
namespace myDatabaseApp
{
class Program{
static void Main(string[] args){
Console.WriteLine("Insert a name into the database:");
string name = Console.ReadLine();
//Code for inserting row in database
Console.WriteLine("You have succesfully inserted the name into the database!");
Console.ReadLine();
}
}
}
我使用我的localhost
作为数据库,我的用户名是root
,我没有密码。
我已经为c#安装了MySQL连接器。我不知道我需不需要它。
粘贴自:https://zetcode.com/csharp/mysql/
static void Main()
{
string cs = @"server=localhost;userid=user12;
password=34klq*;database=mydb";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(cs);
conn.Open();
string stm = "SELECT VERSION()";
MySqlCommand cmd = new MySqlCommand(stm, conn);
string version = Convert.ToString(cmd.ExecuteScalar());
Console.WriteLine("MySQL version : {0}", version);
} catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
} finally
{
if (conn != null)
{
conn.Close();
}
}
}
请记住,您也可以使用ExecuteNonQuery(用于插入/更新/删除等命令)和ExecuteReader(用于返回数据的命令,例如select命令)来代替ExecuteScalar。