ExcelHelper/Views/Pages/SqlQueryPage.xaml.cs

96 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DuckDB.NET.Data;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit;
namespace ExcelHelper.Views.Pages
{
/// <summary>
/// SqlQueryPage.xaml 的交互逻辑
/// </summary>
public partial class SqlQueryPage : Page,IView
{
public SqlQueryPage()
{
InitializeComponent();
// 加载 HL/SQL.xshd
using (var reader = new System.Xml.XmlTextReader("HL/SQL.xshd"))
{
var xshd = HighlightingLoader.LoadXshd(reader);
var highlighting = HighlightingLoader.Load(xshd, HighlightingManager.Instance);
TextEditor.SyntaxHighlighting = highlighting;
}
}
// 替换 DuckDBDataAdapter 使用 DataTable.Load 方法
private void ExecuteButton_Click(object sender, RoutedEventArgs e)
{
StatusTextBlock.Text = "执行中...";
// 获取 SQL 查询文本
string sqlQuery = TextEditor.Text;
// 创建 DuckDB 连接
using (var connection = new DuckDBConnection("DataSource=:memory:"))
{
connection.Open();
try
{
// 执行用户的查询
using (var command = connection.CreateCommand())
{
command.CommandText = sqlQuery;
using (var reader = command.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
// 将结果绑定到 DataGrid
ResultDataGrid.ItemsSource = dataTable.DefaultView;
StatusTextBlock.Text = $"执行完成,共 {dataTable.Rows.Count} 行";
}
}
}
catch (Exception ex)
{
StatusTextBlock.Text = $"查询失败:{ex.Message}";
MessageBox.Show($"查询执行失败:{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
connection.Close();
}
}
private void FunctionListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (FunctionListBox.SelectedItem is ListBoxItem item)
{
var functionText = item.Content.ToString();
var caretOffset = TextEditor.CaretOffset;
TextEditor.Document.Insert(caretOffset, functionText);
}
}
}
}