- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试制作一个 WPF 应用程序。我的窗口内有一个数据网格。我制作了另一个窗口,将新数据添加到我的数据网格中。虽然它按照我想要的方式工作,但我不断遇到异常。我的 MySQL 代码:
using System;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.Windows;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Windows.Controls;
using System.Data;
using Newtonsoft.Json;
namespace TestApp
{
public class MySQLConnection
{
private MySqlConnection connection;
private string server;
private string database;
private string user;
private string password;
private int port;
private string sslM;
private MySqlDataAdapter adp;
private MySqlCommandBuilder builder;
//Constructor
public MySQLConnection()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "pia";
user = "root";
password = "Timjar00";
port = 3306;
sslM = "None";
string connectionString;
connectionString = string.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
public void updateDatatable(DataTable tb,DataGrid dg)
{
try
{
builder = new MySqlCommandBuilder(adp);
adp.Update(tb);
dg.ItemsSource = tb.DefaultView;
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
public DataTable FillDataTable(string query, DataTable tb)
{
if (this.OpenConnection() == true)
{
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
adp = new MySqlDataAdapter(cmd);
adp.Fill(tb);
adp.Dispose();
this.CloseConnection();
}
catch(MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
return tb;
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void CreateTableIfNotExists(string query)
{
//string query = "CREATE TABLE testtable (name varchar(20));";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Insert statement
public void Query(string query)
{
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Insert statement
public void InsertmultipleOne(string query, int amount)
{
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
for(int i = 1; i <= amount; i++)
{
string quer = string.Format(query, i);
MySqlCommand cmd = new MySqlCommand(quer, connection);
//Execute command
cmd.ExecuteNonQuery();
}
//close connection
this.CloseConnection();
}
}
public void InsertmultipleTwo(string query, int amount1, int amount2)
{
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
for (int i = 1; i <= amount1; i++)
{
string quer = string.Format(query, amount2,i);
MySqlCommand cmd = new MySqlCommand(quer, connection);
//Execute command
cmd.ExecuteNonQuery();
}
//close connection
this.CloseConnection();
}
}
public void InsertMultipleThree(string query,string val1, string val2, string val3, string val4, string val5, string val6, string val7, string val8, string val9, bool? val10, bool? val11, bool? val12)
{
if(this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand command = new MySqlCommand(query, connection);
command.Prepare();
command.Parameters.AddWithValue("@DQvalue", val1.ToString());
command.Parameters.AddWithValue("@DQIndexOf", val2.ToString());
command.Parameters.AddWithValue("@DIvalue", val3.ToString());
command.Parameters.AddWithValue("@DIIndexOf", val4.ToString());
command.Parameters.AddWithValue("@AQvalue", val5.ToString());
command.Parameters.AddWithValue("@AQIndexOf", val6.ToString());
command.Parameters.AddWithValue("@AIvalueLoHi", val7.ToString());
command.Parameters.AddWithValue("@AIIndexOf", val8.ToString());
command.Parameters.AddWithValue("@description", val9.ToString());
command.Parameters.AddWithValue("@checkBit", val10);
command.Parameters.AddWithValue("@GND1", val11);
command.Parameters.AddWithValue("@GND2", val12);
//Execute command
command.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Insert statement
public void ReadQueryToComboBox(string query, ComboBox cb,string columnName)
{
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
cb.Items.Add(rdr[columnName]);
}
//Execute command
cmd.ExecuteNonQuery();
rdr.Close();
//close connection
this.CloseConnection();
}
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM tableinfo";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"] + "");
list[1].Add(dataReader["name"] + "");
list[2].Add(dataReader["age"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
//Count statement
public int CountTable(string tablaname)
{
string query = string.Format("SELECT Count(*) FROM {0}", tablaname);
int Count = -1;
//Open Connection
if (this.OpenConnection() == true)
{
//Create Mysql Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//ExecuteScalar will return one value
Count = int.Parse(cmd.ExecuteScalar() + "");
//close Connection
this.CloseConnection();
return Count;
}
else
{
return Count;
}
}
//Backup
public void Backup()
{
try
{
DateTime Time = DateTime.Now;
int year = Time.Year;
int month = Time.Month;
int day = Time.Day;
int hour = Time.Hour;
int minute = Time.Minute;
int second = Time.Second;
int millisecond = Time.Millisecond;
//Save file to C:\ with the current date as a filename
string path;
path = "C:\\MySqlBackup" + year + "-" + month + "-" + day +
"-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
StreamWriter file = new StreamWriter(path);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysqldump";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}",
user, password, server, database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
string output;
output = process.StandardOutput.ReadToEnd();
file.WriteLine(output);
process.WaitForExit();
file.Close();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to backup!");
}
}
//Restore
public void Restore()
{
try
{
//Read file from C:\
string path;
path = "C:\\MySqlBackup.sql";
StreamReader file = new StreamReader(path);
string input = file.ReadToEnd();
file.Close();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "mysql";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = false;
psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}",
user, password, server, database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
process.StandardInput.WriteLine(input);
process.StandardInput.Close();
process.WaitForExit();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to Restore!");
}
}
}
}
我将 FillDataTable()
方法绑定(bind)到我的初始化代码。 DataGrid 已正确填充,但当我打开一个向数据库添加新行的新窗口时,我会再次调用我的 fillDataTable()
函数。
我可以看到函数 updateDatatable()
立即跳转到我的异常,并且我不断收到以下异常:“已经有一个与此连接关联的打开的 DataReader,必须首先关闭它。”对于数据库中的每条记录,如果我有 3 行,将显示 3 个消息框。我在此类中处理所有 MySQL 代码,并在其余代码中使用此类中的函数。
这是 updateDataTable()
函数内的堆栈跟踪:
> TestApp.exe!TestApp.MySQLConnection.updateDatatable(System.Data.DataTable tb, System.Windows.Controls.DataGrid dg) Line 79 C#
TestApp.exe!TestApp.MainWindow.Row_Changed(object sender, System.Data.DataRowChangeEventArgs e) Line 178 + 0x2e bytes C#
System.Data.dll!System.Data.DataTable.OnRowChanged(System.Data.DataRowChangeEventArgs e) + 0x36 bytes
System.Data.dll!System.Data.DataTable.OnRowChanged(System.Data.DataRowChangeEventArgs args, System.Data.DataRow eRow, System.Data.DataRowAction eAction) + 0x4c bytes
System.Data.dll!System.Data.DataTable.RaiseRowChanged(System.Data.DataRowChangeEventArgs args, System.Data.DataRow eRow, System.Data.DataRowAction eAction) + 0xa8 bytes
System.Data.dll!System.Data.DataTable.SetNewRecordWorker(System.Data.DataRow row, int proposedRecord, System.Data.DataRowAction action, bool isInMerge, bool suppressEnsurePropertyChanged, int position, bool fireEvent, out System.Exception deferredException) + 0x21e bytes
System.Data.dll!System.Data.DataTable.InsertRow(System.Data.DataRow row, long proposedID, int pos, bool fireEvent) + 0xf5 bytes
System.Data.dll!System.Data.DataTable.LoadDataRow(object[] values, bool fAcceptChanges) + 0x178 bytes
System.Data.dll!System.Data.ProviderBase.SchemaMapping.LoadDataRow() + 0x67 bytes
System.Data.dll!System.Data.Common.DataAdapter.FillLoadDataRow(System.Data.ProviderBase.SchemaMapping mapping) + 0xc5 bytes
System.Data.dll!System.Data.Common.DataAdapter.FillFromReader(System.Data.DataSet dataset, System.Data.DataTable datatable, string srcTable, System.Data.ProviderBase.DataReaderContainer dataReader, int startRecord, int maxRecords, System.Data.DataColumn parentChapterColumn, object parentChapterValue) + 0xc6 bytes
System.Data.dll!System.Data.Common.DataAdapter.Fill(System.Data.DataTable[] dataTables, System.Data.IDataReader dataReader, int startRecord, int maxRecords) + 0x138 bytes
System.Data.dll!System.Data.Common.DbDataAdapter.FillInternal(System.Data.DataSet dataset, System.Data.DataTable[] datatables, int startRecord, int maxRecords, string srcTable, System.Data.IDbCommand command, System.Data.CommandBehavior behavior) + 0xab bytes
System.Data.dll!System.Data.Common.DbDataAdapter.Fill(System.Data.DataTable[] dataTables, int startRecord, int maxRecords, System.Data.IDbCommand command, System.Data.CommandBehavior behavior) + 0xa1 bytes
System.Data.dll!System.Data.Common.DbDataAdapter.Fill(System.Data.DataTable dataTable) + 0x6d bytes
TestApp.exe!TestApp.MySQLConnection.FillDataTable(string query, System.Data.DataTable tb) Line 93 + 0x10 bytes C#
TestApp.exe!TestApp.MainWindow.FillDatagrid() Line 193 + 0x2e bytes C#
TestApp.exe!TestApp.MainWindow.Add_newRegel(object sender, System.Windows.RoutedEventArgs e) Line 769 + 0x8 bytes C#
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) + 0x74 bytes
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) + 0xae bytes
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args) + 0x73 bytes
PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs e) + 0x18 bytes
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnClick() + 0x4b bytes
PresentationFramework.dll!System.Windows.Controls.Button.OnClick() + 0x55 bytes
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) + 0xa6 bytes
PresentationCore.dll!System.Windows.UIElement.OnMouseLeftButtonUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e) + 0x6c bytes
PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) + 0x30 bytes
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) + 0x2e bytes
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) + 0x3f bytes
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) + 0xae bytes
PresentationCore.dll!System.Windows.UIElement.ReRaiseEventAs(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args, System.Windows.RoutedEvent newEvent) + 0x109 bytes
PresentationCore.dll!System.Windows.UIElement.OnMouseUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e) + 0xc6 bytes
PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) + 0x30 bytes
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) + 0x2e bytes
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) + 0x3f bytes
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) + 0xae bytes
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args) + 0x73 bytes
PresentationCore.dll!System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs args) + 0x46 bytes
PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs args, bool trusted) + 0x1a bytes
PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea() + 0x203 bytes
PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input) + 0x45 bytes
PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport) + 0x62 bytes
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawMouseActions actions, int x, int y, int wheel) + 0x2d6 bytes
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.FilterMessage(System.IntPtr hwnd, MS.Internal.Interop.WindowMessage msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) + 0x428 bytes
PresentationCore.dll!System.Windows.Interop.HwndSource.InputFilterMessage(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) + 0x6b bytes
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) + 0x9b bytes
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) + 0x6b bytes
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) + 0x52 bytes
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) + 0x34 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs) + 0x131 bytes
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam) + 0xee bytes
[Native to Managed Transition]
[Managed to Native Transition]
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) + 0xb1 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x4a bytes
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x5a bytes
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x74 bytes
PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x2b bytes
PresentationFramework.dll!System.Windows.Application.Run() + 0x1c bytes
TestApp.exe!TestApp.App.Main() + 0x59 bytes
我也找到了我的问题所在。在我的主代码中,我执行以下操作:
private void Add_newRegel(object sender, RoutedEventArgs e)
{
ReceptenPopup recept = new ReceptenPopup();
if (recept.ShowDialog() == true)
{
}
else
{
dt.Clear();
receptenDg.ItemsSource = null;
sqlstring = "Select * FROM Recepten";
DataTable mydt = db.FillDataTable(sqlstring, dt);
receptenDg.ItemsSource = mydt.DefaultView;
mydt.RowDeleted += Row_Deleted;
mydt.RowChanged += Row_Changed;
}
}
解释一下:当我打开一个新窗口,填写信息,然后单击“确定”向数据库添加新行时,会调用 else 语句中的代码。代码中出现问题的部分是 DataTable mydt = db.FillDataTable(sqlstring, dt); 部分。我该如何解决这个问题?
最佳答案
连接、命令、数据读取器和 DataAdapter 都是 IDisposable,因此每个都应位于 using
block 中。完成此操作后,您不需要关闭它们,因为它们将在退出 block 时被隐式 Dispose 关闭。
它还保证即使抛出异常也会处理事情,而发布的代码却没有这样做。实现这一目标的任何替代方法最终都比 using
block 更复杂,这使得它变得显而易见。
不再将这些东西作为类级别的字段后,您会发现这些问题将会消失。
附注我建议不要命名一个仅通过大小写与另一个类区分的类。
关于c# - 遇到 MySQL 异常问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53482836/
问题很简单:我正在寻找一种优雅的使用方式 CompletableFuture#exceptionally与 CompletableFuture#supplyAsync 一起.这是行不通的: priva
对于 Web 服务,我们通常使用 maven-jaxb2-plugin 生成 java bean,并在 Spring 中使用 JAXB2 编码。我想知道如何处理 WSDL/XSD 中声明的(SOAP-
这个问题已经有答案了: Array index out of bound behavior (10 个回答) 已关闭 8 年前。 我对下面的 C 代码感到好奇 int main(){
当在类的开头使用上下文和资源初始化 MediaPlayer 对象时,它会抛出 NullPointer 异常,但是当在类的开头声明它时(因此它是 null),然后以相同的方式初始化它在onCreate方
嘿 我尝试将 java 程序连接到 REST API。 使用相同的代码部分,我在 Java 6 中遇到了 Java 异常,并且在 Java 8 中运行良好。 环境相同: 信任 机器 unix 用户 代
我正在尝试使用 Flume 和 Hive 进行 Twitter 分析。为了从 twitter 获取推文,我在 flume.conf 文件中设置了所有必需的参数(consumerKey、consumer
我在 JavaFX 异常方面遇到一些问题。我的项目在我的 Eclipse 中运行,但现在我的 friend 也尝试访问该项目。我们已共享并直接保存到保管箱文件夹中。但他根本无法让它发挥作用。他在控制台
假设我使用 blur() 事件验证了电子邮件 ID,我正在这样做: $('#email').blur(function(){ //make ajax call , check if dupli
我这样做是为了从 C 代码调用非托管函数。 pCallback 是一个函数指针,因此在托管端是一个委托(delegate)。 [DllImport("MyDLL.dll")] public stati
为什么这段代码是正确的: try { } catch(ArrayOutOfBoundsException e) {} 这是错误的: try { } catch(IOException e) {} 这段
我遇到了以下问题:有导出函数的DLL。 代码示例如下:[动态链接库] __declspec(dllexport) int openDevice(int,void**) [应用] 开发者.h: __de
从其他线程,我知道我们不应该在析构函数中抛出异常!但是对于下面的例子,它确实有效。这是否意味着我们只能在一个实例的析构函数中抛出异常?我们应该如何理解这个代码示例! #include using n
为什么需要异常 引出 public static void main(String[
1. Java的异常机制 Throwable类是Java异常类型的顶层父类,一个对象只有是 Throwable 类的(直接或者间接)实例,他才是一个异常对象,才能被异常处理机制识别。JDK中内
我是 Python 的新手,我对某种异常方法的实现有疑问。这是代码(缩写): class OurException(Exception): """User defined Exception"
我已经创建了以下模式来表示用户和一组线程之间的关联,这些线程按他们的最后一条消息排序(用户已经阅读了哪些线程,哪些没有): CREATE TABLE table(user_id bigint, mes
我正在使用 Python 编写一个简单的自动化脚本,它可能会在多个位置引发异常。在他们每个人中,我都想记录一条特定的消息并退出程序。为此,我在捕获异常并处理它(执行特定的日志记录操作等)后引发 Sys
谁能解释一下为什么这会导致错误: let xs = [| "Mary"; "Mungo"; "Midge" |] Array.iter printfn xs 虽然不是这样: Array.iter pr
在我使用 Play! 的网站上,我有一个管理部分。所有 Admin Controller 都有一个 @With 和一个 @Check 注释。 断开连接后,一切正常。连接后,每次加载页面(任何页面,无论
我尝试连接到 azure 表存储并添加一个对象。它在本地主机上工作得很好,但是在我使用的服务器上我得到以下异常及其内部异常: Exception of type 'Microsoft.Wind
我是一名优秀的程序员,十分优秀!