C# VS2022+WinForm+Oracle19.3+Excel,根据数据库表定义书生成SQL
在C#中,使用VS2022创建WinForm应用程序,并结合Oracle 19.3数据库以及Microsoft Excel,可以生成数据库表的SQL定义脚本。以下是一个简化的代码示例,展示了如何连接Oracle数据库并获取表的结构信息,然后将这些信息导出到Excel文件中:
using System;
using System.Data;
using System.Data.OracleClient;
using Excel = Microsoft.Office.Interop.Excel;
namespace OracleToExcel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnExport_Click(object sender, EventArgs e)
{
string connectionString = "User Id=用户名;Password=密码;Data Source=数据库连接信息";
OracleConnection conn = new OracleConnection(connectionString);
conn.Open();
string query = "SELECT * FROM 表名 WHERE ROWNUM = 0"; // 获取表结构
OracleCommand cmd = new OracleCommand(query, conn);
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.FillSchema(dt, SchemaType.Source);
// 导出到Excel
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Add(Type.Missing);
Excel.Worksheet worksheet = null;
excelApp.Visible = false;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "表结构";
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[2, i + 1] = GetSqlType(dt.Columns[i].DataType);
}
// 保存并关闭
workbook.SaveAs(@"C:\path\to\your\excel.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(false, Type.Missing, Type.Missing);
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
worksheet = null;
评论已关闭