DB 연결 관리 개선 및 연결 해제(Dispose) 오류 해결: Helper_DB의 연결 생성 및 해제 로직을 안전하게 리팩토링하고 Search_Infor에서 지역 변수를 사용하도록 수정

This commit is contained in:
2026-01-25 13:56:18 +09:00
parent e3d5674b0a
commit 92f36e78a5
5 changed files with 112 additions and 83 deletions

View File

@@ -9,6 +9,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UniMarc.BaroService_TI;
using UniMarc.Properties;
namespace UniMarc
@@ -16,14 +17,31 @@ namespace UniMarc
public partial class Helper_DB
{
static string cs = "";
public static DataTable ExecuteQueryData(string query)
//static string cs = "";
public enum eDbType
{
unimarc,
cl_marc
}
public static MySqlConnection CreateConnection(eDbType dbtype)
{
var dbname = dbtype.ToString();
string strConnection = string.Format(
"Server={0};" +
"Port={1};" +
$"Database={dbname};" +
"uid={2};" +
"pwd={3};", ServerData[0], DBData[0], DBData[1], DBData[2]);
return new MySqlConnection(strConnection);
}
public static DataTable ExecuteQueryData(string query, MySqlConnection cn = null)
{
var bLocalCN = cn == null;
DataTable dt = new DataTable();
try
{
var cn = new MySqlConnection(cs);
if (cn == null) cn = CreateConnection(eDbType.unimarc);// new MySqlConnection(cs);
var cmd = new MySqlCommand(query, cn);
cn.Open();
using (MySqlDataAdapter adapter = new MySqlDataAdapter(cmd))
@@ -32,7 +50,7 @@ namespace UniMarc
}
cmd.Dispose();
cn.Close();
cn.Dispose();
if (bLocalCN) cn.Dispose();
return dt;
}
catch (Exception ex)
@@ -50,12 +68,12 @@ namespace UniMarc
/// <param name="wheres"></param>
/// <param name="orders"></param>
/// <returns></returns>
public static DataTable GetDT(string tableName, string columns = "*", string wheres = "", string orders = "")
public static DataTable GetDT(string tableName, string columns = "*", string wheres = "", string orders = "", MySqlConnection cn = null)
{
var sql = $"select {columns} from {tableName}";
if (wheres.isEmpty() == false) sql += " where " + wheres;
if (orders.isEmpty() == false) sql += " order by " + orders;
return ExecuteQueryData(sql);
return ExecuteQueryData(sql, cn);
}
@@ -65,16 +83,17 @@ namespace UniMarc
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
public static (int applyCount, string errorMessage) ExcuteNonQuery(string query)
public static (int applyCount, string errorMessage) ExcuteNonQuery(string query, MySqlConnection cn = null)
{
try
{
var cn = new MySqlConnection(cs);
var bLocalCN = cn == null;
if (cn == null) cn = CreateConnection(eDbType.unimarc);//new MySqlConnection(cs);
var cmd = new MySqlCommand(query, cn);
cn.Open();
var cnt = cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Dispose();
if (bLocalCN) cn.Dispose();
return (cnt, string.Empty);
}
catch (Exception ex)
@@ -82,6 +101,38 @@ namespace UniMarc
return (-1, ex.Message);
}
}
/// <summary>
/// Insert 명령을 수행한 후 자동 생성된 index값을 반환합니다.
/// 오류발생시에는 -1을 반환합니다
/// </summary>
/// <param name="cmd"></param>
/// <param name="cn"></param>
/// <returns></returns>
public long DB_Send_CMD_Insert_GetIdx(string cmd, MySqlConnection cn = null)
{
long lastId = -1;
var bLocalCN = cn == null;
try
{
if (cn == null) cn = CreateConnection(eDbType.unimarc);//new MySqlConnection(cs);
using (var sqlcmd = new MySqlCommand(cmd, cn))
{
cn.Open();
sqlcmd.ExecuteNonQuery();
lastId = sqlcmd.LastInsertedId;
}
if (bLocalCN) cn.Dispose();
}
catch (Exception ex)
{
UTIL.MsgE($"데이터베이스 실행오류\n{ex.Message}");
}
return lastId;
}
}
/// <summary>
/// DB접속을 도와주는 클래스
@@ -94,14 +145,14 @@ namespace UniMarc
/// <summary>
/// IP / Port / Uid / pwd
/// </summary>
string[] ServerData = {
static string[] ServerData = {
Settings.Default.IP,
Settings.Default.Uid,
Settings.Default.pwd
};
int port = Settings.Default.Port;
string[] DBData = {
static string[] DBData = {
Settings.Default.dbPort,
Settings.Default.dbUid,
Settings.Default.dbPwd
@@ -111,6 +162,28 @@ namespace UniMarc
MySqlCommand sqlcmd = new MySqlCommand();
MySqlDataReader sd;
public MySqlConnection CreateConnection()
{
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(ServerData[0], port, ServerData[1], ServerData[2]);
connectionInfo.Timeout = TimeSpan.FromSeconds(30);
using (var client = new SshClient(connectionInfo))
{
client.Connect();
if (client.IsConnected)
{
string strConnection = string.Format(
"Server={0};" +
"Port={1};" +
"Database=unimarc;" +
"uid={2};" +
"pwd={3};", ServerData[0], DBData[0], DBData[1], DBData[2]);
return new MySqlConnection(strConnection);
}
}
return null;
}
/// <summary>
/// DB를 사용하고 싶을 때 미리 저장된 DB의 기본 접속정보를 이용하여 DB에 접근한다.
@@ -130,7 +203,7 @@ namespace UniMarc
client.Connect();
if (client.IsConnected)
{
cs = string.Format(
var cs = string.Format(
"Server={0};" +
"Port={1};" +
"Database=unimarc;" +
@@ -141,32 +214,6 @@ namespace UniMarc
}
}
public MySql.Data.MySqlClient.MySqlConnection CreateConnection()
{
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(ServerData[0], port, ServerData[1], ServerData[2]);
connectionInfo.Timeout = TimeSpan.FromSeconds(30);
using (var client = new SshClient(connectionInfo))
{
if (conn != null)
{
conn.Close();
conn.Dispose();
}
client.Connect();
if (client.IsConnected)
{
string strConnection = string.Format(
"Server={0};" +
"Port={1};" +
"Database=unimarc;" +
"uid={2};" +
"pwd={3};", ServerData[0], DBData[0], DBData[1], DBData[2]);
return new MySqlConnection(strConnection);
}
}
return null;
}
/// <summary>
/// 국중DB를 사용하고 싶을 때 미리 저장된 DB의 기본 접속정보를 이용하여 DB에 접근한다.
@@ -295,32 +342,8 @@ namespace UniMarc
}
conn.Close();
}
public int DB_Send_CMD_reVoid(string cmd)
{
var ret = Helper_DB.ExcuteNonQuery(cmd);
if (ret.applyCount == -1) UTIL.MsgE($"데이터베이스 실행오류\n{ret.errorMessage}");
return ret.applyCount;
}
public long DB_Send_CMD_Insert_GetIdx(string cmd)
{
long lastId = -1;
try
{
using (var cn = this.CreateConnection())
{
var sqlcmd = new MySqlCommand(cmd, cn);
cn.Open();
sqlcmd.ExecuteNonQuery();
lastId = sqlcmd.LastInsertedId;
}
}
catch (Exception ex)
{
UTIL.MsgE($"데이터베이스 실행오류\n{ex.Message}");
}
return lastId;
}
/// <summary>
/// DBcon이 선진행되어야함.
/// SELECT * FROM [DB_Table_Name] WHERE [DB_Where_Table] LIKE \"%DB_Search_Data%\"

View File

@@ -163,7 +163,7 @@
this.dataGridView1.RowHeadersWidth = 40;
this.dataGridView1.RowTemplate.Height = 23;
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.Size = new System.Drawing.Size(1310, 478);
this.dataGridView1.Size = new System.Drawing.Size(1638, 597);
this.dataGridView1.TabIndex = 48;
this.dataGridView1.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellDoubleClick);
this.dataGridView1.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dataGridView1_RowPostPaint);

View File

@@ -169,7 +169,7 @@
<data name="bindingNavigatorAddNewItem.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
wQAADsEBuJFr7QAAAVdJREFUOE/Nz0tLAmEUBmB3kWRoCUVEISFUJGb1OywiKrDsIpZdkJAkDUvDQkij
wAAADsABataJCQAAAVdJREFUOE/Nz0tLAmEUBmB3kWRoCUVEISFUJGb1OywiKrDsIpZdkJAkDUvDQkij
UKSbVIvatKhNi9oERRAGEQXhjJdp7Hd83/eGs2jhLGQ20QtndTgP71Gp/m0KZ1XInlTjM6XG+4EG5fuK
yaTUIN8bIMUQ0gmtcuBtX/MLPMT0yoHnuA6kuA4iruI20lAZ+DiswWuyFum4Dk+7dbiP6kHEFVDBg+tQ
My4DLbjwG3DqbcORxygHXxJakGIQRFwDEf0gwjKI4AYtzIHmHaA5Oxg/CsYPIb7YIQced+qluvTLCyIs
@@ -184,7 +184,7 @@
<data name="bindingNavigatorDeleteItem.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
wQAADsEBuJFr7QAAAWtJREFUOE+1kE0ow2Ecx/9X5a2UiwtKOSCTmJBMhuQlMo3IvCUHDouEXHZwIOVC
wAAADsABataJCQAAAWtJREFUOE+1kE0ow2Ecx/9X5a2UiwtKOSCTmJBMhuQlMo3IvCUHDouEXHZwIOVC
DrhIDiQl5USy07zNa2tKf2laaRf84/J8xBCetab4XL/f76fn+SnKX4DrGLqrwbHDzywkWJlHdJYjLEbY
Wg8q4eYKlma+d1hbgF4TotWIaC+FuYmAktcXCksx2HrknBOHX1KbiTDngrXhW0kMdSBM2TA5Io+/wuI0
oiz5TcRwB7hPYazfLx3rDz7+gCsXNBb4v1SdgajTQ19TaOMP2NtFmPSIilSo0v1y7FHBnAdZMWi6aO51
@@ -196,7 +196,7 @@
<data name="bindingNavigatorMoveFirstItem.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
wQAADsEBuJFr7QAAATFJREFUOE9jYBg0oHDW8/9NC57/z5z4+D+6HAyEtz/AKceQO/PZ/1VH3v/HpSi+
wAAADsABataJCQAAATFJREFUOE9jYBg0oHDW8/9NC57/z5z4+D+6HAyEtz/AKceQO/PZ/1VH3v/HpSi+
+8H/4IZrWOXAIGPK0/8L933Aqii+5+H/pfv///evvoAhBwcJPU/+T9vyHkNRRPt9sObMWf//e5WewG1A
ZNej/72rP6AoCm29B9bcuu7/f//Ov/9d8g/gNiCw+eH/uvnv4IqCW+7+X7T3//+Odf//Z8z5+d+u7ud/
+4ztuA3wqLr/P3/aGxRFdsW3/6fP+f3fv+vbf53Cd/8tEtbjNsC+9O7/7MmvMRTpp5z/b1L04r9K1qf/
@@ -207,7 +207,7 @@
<data name="bindingNavigatorMovePreviousItem.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
wQAADsEBuJFr7QAAALtJREFUOE9jYBgyILz9wX90MaJBfPeD/8EN18gzIL7n4f+l+///96++QLoBEe33
wAAADsABataJCQAAALtJREFUOE9jYBgyILz9wX90MaJBfPeD/8EN18gzIL7n4f+l+///96++QLoBEe33
wZozZ/3/71V6gjQDQlvvgTW3rvv/37/z73+X/APEGxDccvf/or3//3es+/8/Y87P/3Z1P//bZ2wn3gAQ
sCu+/T99zu///l3f/usUvvtvkbCeNANAQD/l/H+Tohf/VbI+/TeOXEa6ASBgkHTiv2za1/+6wfPIMwAE
9FMv/9fwnUa+ASCg4jGBMgMGLwAA0BRgmCws/7cAAAAASUVORK5CYII=
@@ -216,7 +216,7 @@
<data name="bindingNavigatorMoveNextItem.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
wQAADsEBuJFr7QAAAKRJREFUOE9jYBh0oHDW8//oYiSB3JnP/id03yPfkIwpT//P2//7f0LXHfIMSeh5
wAAADsABataJCQAAAKRJREFUOE9jYBh0oHDW8//oYiSB3JnP/id03yPfkIwpT//P2//7f0LXHfIMSeh5
8n/2vl//O7f+/e9Wepl0QyK7Hv2fsu3X/5Klf/8nTP/73yb3LGmGBDY//N+69j1Ys3HJl//S0df+G0cu
I94Qj6r7/0vmvoNrVnTpIV4zCNiX3v0f2PKMPM0gYJF3579NwRXyNIOAYdZt8jWDgE7aDfI1D00AAKB+
X6Bjq5qXAAAAAElFTkSuQmCC
@@ -225,7 +225,7 @@
<data name="bindingNavigatorMoveLastItem.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAO
wQAADsEBuJFr7QAAAStJREFUOE9jYBhUoHDW8//oYjAAkmta8Px/5sTHONUw5M589j+h+x5WBSC5VUfe
wAAADsABataJCQAAAStJREFUOE9jYBhUoHDW8//oYjAAkmta8Px/5sTHONUw5M589j+h+x5WBSC5VUfe
/w9vf4BVHgwypjz9P2//7/8JXXcwFIHkFu778D+44RqGHBwk9Dz5P3vfr/+dW//+dyu9jKIQJDdty/v/
/tUXcBsQ2fXo/5Rtv/6XLP37P2H63/82uWfhikFyvas//PcqPYHbgMDmh/9b174HazYu+fJfOvraf+PI
ZWANILm6+e/+u+QfwG2AR9X9/yVz38E1K7r0wBWD5PKnvflvn7EdtwH2pXf/B7Y8w9AMk8ue/Pq/RcJ6

View File

@@ -28,7 +28,7 @@
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
this.label1 = new System.Windows.Forms.Label();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.idx = new System.Windows.Forms.DataGridViewTextBoxColumn();
@@ -102,14 +102,14 @@
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("굴림", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle2.Font = new System.Drawing.Font("굴림", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));
dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.idx,
@@ -225,7 +225,7 @@
//
// label2
//
this.label2.Location = new System.Drawing.Point(341, -3);
this.label2.Location = new System.Drawing.Point(363, 9);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(41, 12);
this.label2.TabIndex = 5;

View File

@@ -14,7 +14,7 @@ namespace UniMarc
public partial class Search_Infor : Form
{
Main main;
Helper_DB db = new Helper_DB();
//Helper_DB db = new Helper_DB();
public string compidx;
public Search_Infor(Main _main)
{
@@ -24,7 +24,7 @@ namespace UniMarc
}
private void Search_Infor_Load(object sender, EventArgs e)
{
db.DBcon();
//db.DBcon();
string[] area = { "자체 DB", "국립 중앙 도서관" };
cb_data_area.Items.AddRange(area);
@@ -41,6 +41,8 @@ namespace UniMarc
string tQuery = MakeWHEREQurey();
if (cb_data_area.SelectedIndex == 0)
{
Helper_DB db = new Helper_DB();
db.DBcon();
//(string target, string searchText) = setting_target(true);
@@ -59,6 +61,7 @@ namespace UniMarc
}
else if (cb_data_area.SelectedIndex == 1)
{
Helper_DB db = new Helper_DB();
db.DBcon_cl();
// -user date 비고2
string Area = "`idx`, `grade`, `isbn`, `book_name`, `series`, `author`, "
@@ -403,6 +406,7 @@ namespace UniMarc
if (cb_data_area.SelectedIndex == 0)
{
Helper_DB db = new Helper_DB();
db.DBcon();
filter.Add("작성자");
filter.Add("날짜");
@@ -429,6 +433,7 @@ namespace UniMarc
}
else
{
Helper_DB db = new Helper_DB();
db.DBcon_cl();
cbUser.Items.Clear();
cbUser.Items.Add("전체");
@@ -447,6 +452,7 @@ namespace UniMarc
private void cb_filter_SelectedIndexChanged(object sender, EventArgs e)
{
Helper_DB db = new Helper_DB();
cb_filterDetail.Items.Clear();
cb_filterDetail.Enabled = true;