【发布时间】:2014-05-08 12:50:50
【问题描述】:
我有一个简单的程序,试图在 WPF/C# 应用程序中显示一个 MySQL 表。现在,由于某种原因,我似乎遇到了连接问题,我无法弄清楚它是什么。
我的主窗口:
<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Szuper adatbázisfeltöltő" Height="267.143" Width="525">
<Grid>
<TabControl HorizontalAlignment="Left" Height="236" VerticalAlignment="Top" Width="517">
<TabItem Header="Adatbázis">
<Grid Background="#FFE5E5E5">
<DataGrid x:Name="dataGrid1" ItemsSource="{Binding}" AutoGenerateColumns="True" HorizontalAlignment="Left" Margin="3,10,0,0" VerticalAlignment="Top" Height="119" Width="441"/>
<Button Content="Új rekord" HorizontalAlignment="Left" Margin="0,134,0,0" VerticalAlignment="Top" Width="75"/>
<Button Content="Frissítés" HorizontalAlignment="Left" Margin="80,134,0,0" VerticalAlignment="Top" Width="75"/>
<Button Content="Törlés" HorizontalAlignment="Left" Margin="160,134,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</TabItem>
<TabItem Header="Adminisztráció">
<Grid Background="#FFE5E5E5"/>
</TabItem>
</TabControl>
</Grid>
</Window>
当我运行程序时会发生什么:
public MainWindow()
{
InitializeComponent();
UpdateGrid();
}
public void UpdateGrid()
{
// dataGrid1.DataContext = Class1.getTable().DefaultView;
//dataGrid1.SelectedValuePath = "index";
}
}
魔法应该发生的地方:
class Class1
{
static String str = "Server=http://mysql10.000webhost.com;Database=a2116591_adat;Uid=a2116591_tkis;Pwd=zseton22";
static MySqlConnection con = null;
public static DataTable getTable()
{
//MySqlDataReader Object
MySqlDataReader reader = null;
try
{
con = new MySqlConnection(str);
con.Open(); //open the connection
//We will need to SELECT all or some columns in the table
//via this command
String cmdText = "SELECT * FROM adat";
MySqlCommand cmd = new MySqlCommand(cmdText, con);
reader = cmd.ExecuteReader(); //execute the reader
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
}
catch (MySqlException err)
{
Console.WriteLine("Error: " + err.ToString());
return null;
}
finally
{
if (reader != null)
{
reader.Close();
}
if (con != null)
{
con.Close(); //close the connection
}
}
}
}
}
我尝试改变连接字符串,但无济于事,我有点卡住了。
【问题讨论】:
-
澄清一下,错误发生在 Class1 的第 26 行 - 在 con.Open();
-
如果问题与数据库连接有关,请围绕该问题表达您的问题并删除其他所有内容。见stackoverflow.com/help/mcve
-
我不知道是什么问题。它只是说:MySql.Data.dll 中发生了“MySql.Data.MySqlClient.MySqlException”类型的第一次机会异常错误:MySql.Data.MySqlClient.MySqlException (0x80004005):无法连接到任何指定的 MySQL 主机。
标签: c# mysql wpf binding datagrid