Database query C# not working

荒凉一梦 提交于 2019-12-07 18:26:16

问题


I've read many ODBC tutorials for C# on the net, and this code is the only one that didn't give me error. But the problem is, it doesn't do anything -.- How to fix ??

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());
    }
}
}

回答1:


You need to execute the command:

myCommand.ExecuteNonQuery();



回答2:


Allow me to tidy; important points:

  • using to ensure proper disposal
  • setting the command's Connection
  • executing the command with ExecuteNonQuery()

Code:

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);
}


来源:https://stackoverflow.com/questions/4232943/database-query-c-sharp-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!