我是C#的新手,我只是使用mysql创建数据库连接。然后我需要在这里定义一个数据库连接类,这是我的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace restsurant_pos
{
class mysqlDbConnect
{
public static MySqlConnection GetConnection(){
string MyConnectionString = "Server=Localhost;Database=pos;Uid=root;Pwd='';";
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
return connection;
}
希望它是正确的..
然后如何使用此类创建对象。我刚刚创建了如下所示,但它出现了错误。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace restsurant_pos
{
public partial class AddCategory : Form
{
public AddCategory()
{
InitializeComponent();
}
private void btn_insertCategory_Click(object sender, EventArgs e)
{
string categoryName = txtCategoryName.Text;
mysqlDbConnect connection = new mysqlDbConnect();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO categories(name) VALUES(@categoryName)";
cmd.Parameters.AddWithValue("categoryName", txtCategoryName.Text);
cmd.ExecuteNonQuery();
this.Close();
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open) {
connection.Close();
}
}
}
}
}
我的代码有什么问题..请帮忙
答案 0 :(得分:2)
您尚未为type
提供cmd
。
通过将其(懒惰地)声明为var cmd = connection.CreateCommand()
或使用硬编码类型来解决它。