我正在尝试使用 C# 控制台应用程序同时将数据实现到 2 个(后来是 3 个)表中。我想在表“用户”中实现名字、姓氏和用户ID,用户ID将自动递增。
同样的 userID 也应该与 porilfeID(再次通过自动增量自动完成)和 profileName 一起实现到表“profile”中。
但在某个地方它会抛出命令文本未正确初始化的错误,我无法再弄清楚我做错了什么。
class SQLCreate { public void create(int entries) { string ConnectionString = "server=localhost;uid=root;pwd=;database=databaseassignment;"; MySqlConnection conn; MySqlCommand cmd; MySqlDataAdapter adapter; conn = new MySqlConnection(); int entryValue = entries; conn.ConnectionString = ConnectionString; try { Stopwatch stopw = new Stopwatch(); stopw.Start(); conn.Open(); cmd = new MySqlCommand(); adapter = new MySqlDataAdapter(); cmd.Connection = conn; for (int i = 0; i < entryValue; i++) { MySqlCommand cmd1 = new MySqlCommand("INSERT INTO user (firstName, lastName) VALUES (@firstName, @lastName)", conn); //MySqlCommand cmd1 = new MySqlCommand("INSERT INTO user (firstName, lastName) VALUES (@firstName, @lastName)", conn); cmd1.Parameters.AddWithValue("@firstName", "John"); cmd1.Parameters.AddWithValue("@lastName", "Doe"); cmd1.CommandType = CommandType.Text; int userId = Convert.ToInt32(cmd1.ExecuteScalar()); MySqlCommand cmd2 = new MySqlCommand("INSERT INTO profile (userId, profileName) VALUES (@userId, @profileName)", conn); cmd2.Parameters.AddWithValue("@userId", userId); cmd2.Parameters.AddWithValue("@profileName", "John Doe"); cmd2.CommandType = CommandType.Text; cmd2.ExecuteNonQuery(); string firstName = Faker.Name.First(); string lastName = Faker.Name.Last(); string profileName = Faker.Name.First(); cmd.Parameters.Add("@firstName", MySqlDbType.String); cmd.Parameters["@firstName"].Value = firstName; cmd.Parameters.Add("@lastName", MySqlDbType.String); cmd.Parameters["@lastName"].Value = lastName; cmd.Parameters.Add("@profileName", MySqlDbType.String); cmd.Parameters["@profileName"].Value = profileName; cmd.ExecuteNonQuery(); } conn.Close(); stopw.Stop(); Console.WriteLine(" Time elapsed: {0} ", stopw.Elapsed); } catch (MySql.Data.MySqlClient.MySqlException ex) { Console.WriteLine(ex.Message); } } } }
P粉3373859222024-04-05 18:22:36
您创建 cmd = new MySqlCommand();
但从未设置其 .CommandText
属性。调用 cmd.ExecuteNonQuery();
将失败,因为没有 CommandText
可以执行。
设置 cmd.CommandText
或将构造函数更改为 cmd = new MySqlCommand("text here", conn);
。