数据库查询C#无法正常工作

时间:2010-11-20 13:27:17

标签: c# mysql odbc

我在网上读过很多关于C#的ODBC教程,而这段代码是唯一一个没有给我错误的代码。但问题是,它没有做任何事情 - .-如何解决?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Data.Odbc;
using System.Data.Sql;
namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
        string connectionString = "Server=localhost;User       ID=root;Password=****;Database=testing;Port=3306;Pooling=false";
        MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(connectionString);

        connection.Open();

        string insertQuery = "ALTER TABLE `user` ADD lol INT (15)";
        MySql.Data.MySqlClient.MySqlCommand myCommand = new MySql.Data.MySqlClient.MySqlCommand(insertQuery);
        connection.Close();
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}
}

2 个答案:

答案 0 :(得分:2)

您需要执行命令:

myCommand.ExecuteNonQuery();

答案 1 :(得分:2)

请允许我整理;重点:

  • using以确保妥善处置
  • 设置命令的Connection
  • 使用ExecuteNonQuery()
  • 执行命令

代码:

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string connectionString = "Server=localhost;User ID=root;Password=****;Database=testing;Port=3306;Pooling=false";
string insertQuery = "ALTER TABLE `user` ADD lol INT (15)";
using(MySql.Data.MySqlClient.MySqlConnection connection =
    new MySql.Data.MySqlClient.MySqlConnection(connectionString))
using(MySql.Data.MySqlClient.MySqlCommand myCommand =
    new MySql.Data.MySqlClient.MySqlCommand(insertQuery))
{
    myCommand.Connection = connection;
    connection.Open();
    myCommand.ExecuteNonQuery();
    connection.Close();
}
using(Form1 form1 = new Form1()) {
    Application.Run(form1);
}