我想排除显示特定数据库,但我排除的项目仍会在运行程序时显示。没有编译错误。
private ComboBox cb;
private Label label;
private object[] databases;
public MForm() {
string connectionString =
"Server=localhost;" +
"Database=information_schema;" +
"User ID=root;" +
"Password=root;" +
"Pooling=false";
IDbConnection dbcon;
dbcon = new MySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
string sql = "SELECT COUNT(*) as count FROM information_schema.SCHEMATA"; //count the databases(string) and names it count
dbcmd.CommandText = sql; //sends the string to sql
IDataReader reader = dbcmd.ExecuteReader(); //assign the function to reader
reader.Read(); //uses its getter(Read)
int count = Convert.ToInt32(reader["count"]); //converts the "count"(column) to integer
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
databases = new object[count];
dbcmd = dbcon.CreateCommand();
sql = "show databases";
dbcmd.CommandText = sql;
reader = dbcmd.ExecuteReader();
int i = 0;
while(reader.Read()) {
if((string) databases[i] != "information_schema" &&(string)databases[i] != "sakila" && (string)databases[i] != "enrollmentsystem" && (string)databases[i] != "mysql" &&
(string)databases[i] != "world" && (string)databases[i] != "performance_schema"){
databases[i] = (string) reader["Database"];
i++;
}
}
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbcon.Close();
dbcon = null;
Text = "School Year";
Size = new Size(340, 240);
cb = new ComboBox();
cb.Parent = this;
cb.Location = new Point(50, 30);
cb.Items.AddRange(databases);
cb.SelectionChangeCommitted += new EventHandler(OnChanged);
label = new Label();
label.Location = new Point(80, 170);
label.Parent = this;
label.Text = "...";
CenterToScreen();
}
void OnChanged(object sender, EventArgs e) {
ComboBox combo = (ComboBox) sender;
label.Text = combo.Text;
}
}
class MApplication {
public static void Main() {
Application.Run(new MForm());
}
}
答案 0 :(得分:1)
你的逻辑错误。我假设这些都是不想要添加到数组中的表名。
databases
数组,并且其中的所有元素都为空(或为空?),因此不会满足这些条件。将所有||
更改为&&
,并将其与您在阅读器中返回的数据进行比较:
while (reader.Read())
{
var database = reader["Database"].ToString();
if ((database != "information_schema" && database != "sakila" &&
database != "enrollmentsystem" && database != "mysql" &&
database != "world" && database != "performance_schema")
{
databases[i] = database;
i++;
}
}
我认为一些LINQ并使用List<string>
会使这更容易阅读。它还可以消除第一个查询的需要,该查询获取用于在数组中分配空间的计数。
var databases = new List<string>();
var excludedDatabases =
new List<string> { "information_schema", "sakila", "enrollmentsystem",
"mysql", "world", "performance_schema" };
while (reader.Read())
{
var database = reader["Database"].ToString();
if (!excludedDatabases.Contains(database))
databases.Add(database);
}