简体   繁体   English

数据库连接不起作用C#

[英]Database connection doesn't work C#

I'm working on a program in C#. 我正在使用C#编写程序。 I created a database with MySQL on phpMyAdmin and I want to connect this database with my program. 我在phpMyAdmin上使用MySQL创建了一个数据库,我想将此数据库与程序连接。 After the connection I have to insert, update, delete and view all the data, but I have a problem: the connection doesn't work. 连接后,我必须插入,更新,删除和查看所有数据,但是我有一个问题:连接不起作用。

I post here my code for the connection: 我在这里发布我的连接代码:

public static string StringaConnessione = "Data Source=localhost;Database=agility;userid=root;password='';";
public static MySqlConnection Connessione = new MySqlConnection(StringaConnessione);

When I write the code for the insert button I have another problem (is certainly for the database) 当我为插入按钮编写代码时,我还有另一个问题(肯定是数据库问题)

Connessione.Open();
SQLDataAdapter SDA=new SqlDataAdapter("INSERT INTO GARA(nome_gara,giudice,località,data,tpsopm,tpmopm,tpstot,tpmtot)VALUES('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"','"+textBox8.Text+"')",Connessione);
SDA.SelectCommand.ExecuteNonQuery();
Connessione.Close();
MessageBox.Show("Dati salvati correttamente!");

May you help me, please? 你能帮我吗? Thank you! 谢谢!

You can't use a SqlDataAdapter to talk to MySQL as that class is designed for use with Sql Server. 您不能使用SqlDataAdapterMySQL ,因为该类是为与Sql Server一起使用而设计的。

Use the MySqlDataAdapter instead. 请改用MySqlDataAdapter

You have so many problems with your code: 您的代码有很多问题:

1) You are using static connection, there is Connection pool and it is your friend. 1)您正在使用静态连接,有连接池,它是您的朋友。

2) You are not using your connection in using block or in try/catch/finally/block to ensure closing of connection on exception. 2)您没有在使用block或try / catch / finally / block中使用您的连接,以确保在异常时关闭连接。

3) Blocker problem : You are using SqlDataAdapter instead of MySqlDataAdapter 3) 阻止程序问题 :您正在使用SqlDataAdapter而不是MySqlDataAdapter

4) Blocker problem You should define your Insert query in InsertCommand of the DataAdapter , it will not work with SelectCommand . 4) 阻止程序问题您应该在DataAdapter InsertCommand中定义您的Insert查询,它将不适用于SelectCommand Even better just use MySqlCommand and ExecuteNonQuery on it. 更好的是,仅使用MySqlCommandExecuteNonQuery

5) You are not protected from Sql Injection(Use MySqlCommand.Parameters) 5)您不受SQL注入保护(使用MySqlCommand.Parameters)

6) Bad formatting of your variables, textboxes and db fields. 6)变量,文本框和数据库字段的格式错误。

How your code will look optimally: 您的代码的最佳外观:

public static string connetionString= "Data Source=localhost;Database=agility;userid=root;password='';";

public void SomeMethod()
{

    using(MySqlConnection conn = new MySqlConnection(connetionString));
    {
         conn.Open();

         string query = @"INSERT INTO GARA
                             (nome_gara, giudice, località, data, tpsopm, tpmopm, tpstot, tpmtot)
                          VALUES
                             (@Param1, @Param2, @Param3, @Param4, @Param5, @Param6, @Param7, @Param8)";

         MySqlCommand cmd = new MySqlCommand(@"query", conn);
         cmd.Parameters.AddWithValue("@Param1", textBox1.Text);
         cmd.Parameters.AddWithValue("@Param2", textBox2.Text);
         cmd.Parameters.AddWithValue("@Param3", textBox3.Text);
         cmd.Parameters.AddWithValue("@Param4", textBox4.Text);
         cmd.Parameters.AddWithValue("@Param5", textBox5.Text);
         cmd.Parameters.AddWithValue("@Param6", textBox6.Text);
         cmd.Parameters.AddWithValue("@Param7", textBox7.Text);
         cmd.Parameters.AddWithValue("@Param8", textBox8.Text);

         cmd.ExecuteNonQuery();
    }

}

i think you should discard all your code. 我认为您应该丢弃所有代码。 and find a valid one to start 并找到一个有效的开始

for example this http://roboardgod.blogspot.hk/2013/08/cmysql.html 例如这个http://roboardgod.blogspot.hk/2013/08/cmysql.html

you may need to add the reference MySql.Data.MySqlClient manually. 您可能需要手动添加引用MySql.Data.MySqlClient。 check this post to add the reference How do I add a reference to the MySQL connector for .NET? 检查此帖子以添加参考如何添加对.NET的MySQL连接器的参考?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace MySQLtest
{
    class Program
    {
        static void Main(string[] args)
        {   string dbHost = "";//db address, for example localhost
            string dbUser = "";//dbusername
            string dbPass = "";//dbpassword
            string dbName = "";//db name
            string connStr = "server=" + dbHost + ";uid=" + dbUser + ";pwd=" + dbPass + ";database=" + dbName;
            MySqlConnection conn = new MySqlConnection(connStr);
            MySqlCommand command = conn.CreateCommand();
            conn.Open();

            String cmdText = "SELECT * FROM member WHERE level < 50";
            MySqlCommand cmd = new MySqlCommand(cmdText, conn);
            MySqlDataReader reader = cmd.ExecuteReader(); //execure the reader
            while (reader.Read())
            {
                for (int i = 0; i < 4; i++)
                {
                    String s = reader.GetString(i);
                    Console.Write(s + "\t");
                }
                Console.Write("\n");
            }


            Console.ReadLine();
            conn.Close();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM