ソース掲示板




すべてから検索

キーワード   条件 表示 現行ログ 過去ログ トピックス 名前 本文
CSVインポート & DB更新アプリ
日時: 2007/07/21 15:59
名前: lightbox



データベース
拡張子:
MySQL 5.1.11-beta
データ
拡張子:
社員コード,氏名,フリガナ,所属,性別,作成日,更新日
0001,劇団 一人,ゲキダン ヒトリ,0001,1,2005/09/12,2007/06/01 11:57:05
0002,山村 洋代,ヤマムラ ヒロヨ,0003,1,2005/06/17,2005/09/18
0003,多岡 冬行,タオカ フユユキ,0002,0,2005/08/14,2005/11/14
0004,高田 冬美,タカタ フユミ,0003,1,2005/06/13,2005/10/05
0005,内高 友之,ウチタカ トモユキ,0003,0,2005/09/12,2005/11/10
社員マスタ
列名型値型定数型名最大桁精度スケールNULL主キーデフォルト型説明備考
1社員コード129adCharvarchar8N1文字列値
2氏名129adCharvarchar100文字列値
3フリガナ129adCharvarchar100文字列値
4所属129adCharvarchar8文字列値
5性別3adIntegerint114 バイトの符号付き整数
6作成日135adDBTimeStampdatetime日付/時刻スタンプ
7更新日135adDBTimeStampdatetime日付/時刻スタンプ
メンテナンス

VB.NET : CSVインポート & DB更新アプリ ( No.1 )
日時: 2007/07/21 20:23
名前: lightbox


日時: 2007/07/21 20:23
名前: lightbox
拡張子:
Imports System.Data.Odbc
Imports System.IO
Imports System.Text
Imports System.Windows.Forms

Module MyModule

' ********************************************************
' 実行
' ********************************************************
Sub Main()

      ' ============================================
      ' コンストラクタの呼び出し
      ' ============================================
      Dim lb As lightbox = New lightbox( _
            "Driver={MySQL ODBC 3.51 Driver};" + _
            "SERVER=localhost;" + _
            "DATABASE=mydb;" + _
            "UID=root;" + _
            "PWD=" )

      ' ============================================
      ' プログラムが存在するディレクトリを取得
      ' ============================================
      Dim pgDir As String = lb.GetProgramDir()
      MessageBox.Show( pgDir )

      ' ============================================
      ' 変換したパスを初期ディレクトリとして設定
      ' ============================================
      Dim dlg As New Windows.Forms.OpenFileDialog
      dlg.InitialDirectory = pgDir
      dlg.Filter = "インポート用CSV|*.csv|全て|*.*"
      dlg.FilterIndex = 2
      dlg.RestoreDirectory = True

      ' 列名保存用配列
      Dim aDataName As String()
      ' データ名用配列
      Dim aDataValue As String()
      ' ファイルの中身用
      Dim myStream As Stream
      ' SQL 作成用
      Dim str As String = ""
      ' 存在チェック用
      Dim strQuery As String = ""
      ' ============================================
      ' ファイルを開くダイアログを表示
      ' ============================================
      If dlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
            ' ============================================
            ' myStream としてファイルの中身を取得
            ' ============================================
            myStream = dlg.OpenFile()
            If Not (myStream Is Nothing) Then
                  ' ============================================
                  ' DB 接続
                  ' ============================================
                  if Not lb.Connect() then
                        myStream.Close()
                        MessageBox.Show( "接続失敗の為、終了します   " )
                        End
                  end if

                  ' ============================================
                  ' myStream を読む為の StreamReader クラスを作成
                  ' ファイルは Shift_JIS なので明示する必要がある
                  ' ============================================
                  Dim sr As StreamReader = _
                        New StreamReader( _
                              myStream, _
                              Encoding.GetEncoding("Shift_JIS") _
                        )

                  ' ============================================
                  ' ループ処理で行を結合して、SQL 文を作成
                  ' ============================================
                  Dim nCounter As Integer = 0
                  Dim I As Integer

                  Do While sr.Peek() >= 0
                        If nCounter = 0 Then
                              aDataName = lb.GetArray(sr.ReadLine(),",")
                        Else
                              aDataValue = lb.GetArray(sr.ReadLine(),",")

                              strQuery = "select * from 社員マスタ where "
                              strQuery += "社員コード = '" + aDataValue(0) + "'"
                              if lb.ExistData( strQuery ) then
                                    ' update 作成
                                    str = "update 社員マスタ set "
                                    For I = 0 To aDataName.Length - 1
                                          ' データ内のシングルクォートの処理
                                          aDataValue(I) = aDataValue(I).Replace("'", "''")
                                          If I <> 0 Then
                                                str += ","
                                          End If
                                          If I < 4 Then
                                                str += aDataName(I)
                                                str += " = '"
                                                str += aDataValue(I)
                                                str += "'"
                                          End If
                                          If I = 4 Then
                                                str += aDataName(I)
                                                str += " = "
                                                str += aDataValue(I)
                                          End If
                                          If I > 4 Then
                                                str += aDataName(I)
                                                str += " = '"
                                                str += aDataValue(I)
                                                str += "'"
                                          End If
                                    Next
                                    str += " where 社員コード = "
                                    str += "'" + aDataValue(0) + "'"
                              else
                                    ' insert 作成
                                    str = "insert into 社員マスタ ("
                                    For I = 0 To aDataName.Length - 1
                                          If I <> 0 Then
                                                str += ","
                                          End If
                                          str += aDataName(I)
                                    Next
                                    str += ") values("
                                    For I = 0 To aDataName.Length - 1
                                          ' データ内のシングルクォートの処理
                                          aDataValue(I) = aDataValue(I).Replace("'", "''")
                                          If I <> 0 Then
                                                str += ","
                                          End If
                                          If I < 4 Then
                                                str += "'"
                                                str += aDataValue(I)
                                                str += "'"
                                          End If
                                          If I = 4 Then
                                                str += aDataValue(I)
                                          End If
                                          If I > 4 Then
                                                str += "'"
                                                str += aDataValue(I)
                                                str += "'"
                                          End If
                                    Next
                                    str += ")"
                              end if

                              MessageBox.Show(str)
                              lb.UpdateDB(str)

                        End If
                        nCounter += 1

                  Loop

                  ' ============================================
                  ' リーダとストリームを閉じる
                  ' ============================================
                  sr.Close()
                  myStream.Close()

                  ' ============================================
                  ' 接続解除
                  ' ============================================
                  lb.Close()

            End If
      End If


End Sub



' <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' 処理クラス
' <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Public Class lightbox

      ' 接続オブジェクト
      Private Dim myCon As OdbcConnection = New OdbcConnection
      ' コマンドオブジェクト
      Private Dim myCommand As OdbcCommand = New OdbcCommand
      ' 接続文字列
      Public Dim strCon As String = String.Empty

      ' ********************************************************
      ' コンストラクタの定義( Sub で定義する )
      ' ********************************************************
      Public Sub New( ByVal str As String )

            strCon = str

      End Sub

      ' ********************************************************
      ' 接続処理
      ' ********************************************************
      Public Function Connect() As Boolean

            Connect = True

            ' 接続文字列セット
            myCon.ConnectionString = strCon

            ' ====================================================
            ' 例外処理
            ' ====================================================
            Try
                  ' 接続
                  myCon.Open()
            Catch ex As Exception
                  Connect = False
                  MessageBox.Show( ex.Message )
            End Try

            ' コマンドオブジェクトを接続に関係付ける
            myCommand.Connection = myCon

      End Function

      ' ********************************************************
      ' 接続解除処理
      ' ********************************************************
      Public Sub Close()

            myCon.Close()

      End Sub

      ' ********************************************************
      ' 配列化関数
      ' ********************************************************
      Public Function GetArray(ByVal str As String,ByVal d As String) As String()

            ' 区切り文字定義
            Dim delimStr As String = d
            Dim delimiter As Char() = delimStr.ToCharArray()
            ' 分解
            Dim aRet As String() = str.Split(delimiter)

            Return aRet

      End Function

      ' ********************************************************
      ' 存在チェック
      ' ********************************************************
      Public Function ExistData(ByVal strQuery As String) As Boolean

            Dim myReader As OdbcDataReader

            ' コマンドセット
            myCommand.CommandText = strQuery

            ' ====================================================
            ' 例外処理
            ' ====================================================
            Try
                  ' リーダーオブジェクト取得
                  myReader = myCommand.ExecuteReader()
            Catch ex As Exception
                  myCon.Close()
                  MessageBox.Show( ex.Message )
                  End
            End Try

            ExistData = myReader.HasRows
            myReader.Close()

      End Function

      ' ********************************************************
      ' 更新関数
      ' ********************************************************
      Public Function UpdateDB(ByVal strExec As String) As Boolean

            myCommand.CommandText = strExec
            ' ====================================================
            ' 例外処理
            ' ====================================================
            Try
                  ' 実行
                  myCommand.ExecuteNonQuery()
            Catch ex As Exception
                  myCon.Close()
                  MessageBox.Show( ex.Message )
                  End
            End Try

            Return True

      End Function

      ' ********************************************************
      ' プログラムが実行されているディレクトリを取得
      ' ********************************************************
      Public Function GetProgramDir( ) As String

            Dim ab As Reflection.Assembly = Reflection.Assembly.GetExecutingAssembly()
            Dim md As Reflection.Module = ab.GetModules()(0)
            ' **************************************************************
            ' ディレクトリ部分を取得(  System.IO.Path.GetDirectoryName が簡単 )
            ' **************************************************************
            Dim aDataDir As String() = Getarray( md.FullyQualifiedName, "\" )
            Dim pgDir As String = String.Join("\", aDataDir, 0, aDataDir.Length - 1)

            Return pgDir

      End Function

End Class

End Module
このアーティクルの参照用URLをクリップボードにコピー メンテナンス
C# Console (1) : 最低限のスケルトン ( No.2 )
日時: 2007/07/21 18:48
名前: lightbox
拡張子:
using System.Data.Odbc;
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

// ********************************************************
// * 実行
// ********************************************************
public class App
{

	public static void Main() {

	}

}

// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// 処理クラス
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
public class lightbox
{

	// 接続オブジェクト
	private OdbcConnection myCon = new OdbcConnection();
	// コマンドオブジェクト
	private OdbcCommand myCommand = new OdbcCommand();
	// 接続文字列
	public String strCon = String.Empty;

	// ********************************************************
	// コンストラクタの定義( クラスと同名 )
	// ********************************************************
	public lightbox( String str ) {

		strCon = str;

	}

}
このアーティクルの参照用URLをクリップボードにコピー メンテナンス
C# Console (2) : 処理クラス実装 ( No.3 )
日時: 2007/07/21 19:39
名前: lightbox
拡張子:
using System.Data.Odbc;
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

// ********************************************************
// * 実行
// ********************************************************
public class App
{

	public static void Main() {

	}

}

// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// 処理クラス
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
public class lightbox
{

	// 接続オブジェクト
	private OdbcConnection myCon = new OdbcConnection();
	// コマンドオブジェクト
	private OdbcCommand myCommand = new OdbcCommand();
	// 接続文字列
	public String strCon = String.Empty;

	// ********************************************************
	// コンストラクタの定義( クラスと同名 )
	// ********************************************************
	public lightbox( String str ) {

		strCon = str;

	}

	// ********************************************************
	// 接続処理
	// ********************************************************
	public bool Connect() {

		bool bRet = true;

		// 接続文字列セット
		myCon.ConnectionString = strCon;

		// ====================================================
		// 例外処理
		// ====================================================
		try {
			// 接続
			myCon.Open();
		}
		catch( Exception ex ) {
			bRet = false;
			MessageBox.Show( ex.Message );
		}

		// コマンドオブジェクトを接続に関係付ける
		myCommand.Connection = myCon;

		return bRet;

	}

	// ********************************************************
	// 接続解除処理
	// ********************************************************
	public void Close() {

		myCon.Close();

	}

	// ********************************************************
	// 配列化関数
	// ********************************************************
	public String[] GetArray(String str,String d) {

		// 区切り文字定義
		String delimStr = d;
		Char[] delimiter = delimStr.ToCharArray();
		// 分解
		String[] aRet = str.Split(delimiter);

		return aRet;

	}

	// ********************************************************
	// 存在チェック
	// ********************************************************
	public bool ExistData(String strQuery) {

		OdbcDataReader myReader = null;
		bool bRet = true;

		// コマンドセット
		myCommand.CommandText = strQuery;

		// ====================================================
		// 例外処理
		// ====================================================
		try {
			// リーダーオブジェクト取得
			myReader = myCommand.ExecuteReader();
		}
		catch( Exception ex ) {
			myCon.Close();
			MessageBox.Show( ex.Message );
			System.Environment.Exit( 0 );
		}

		bRet = myReader.HasRows;
		myReader.Close();

		return bRet;

	}

	// ********************************************************
	// 更新関数
	// ********************************************************
	public bool UpdateDB(String strExec) {

		myCommand.CommandText = strExec;
		// ====================================================
		// 例外処理
		// ====================================================
		try {
			// 実行
			myCommand.ExecuteNonQuery();
		}
		catch( Exception ex ) {
			myCon.Close();
			MessageBox.Show( ex.Message );
			System.Environment.Exit( 0 );
		}

		return true;

	}

	// ********************************************************
	// プログラムが実行されているディレクトリを取得
	// ********************************************************
	String GetProgramDir( ) {

		System.Reflection.Assembly ab = System.Reflection.Assembly.GetExecutingAssembly();
		System.Reflection.Module md = ab.GetModules()[0];
		// **************************************************************
		// ディレクトリ部分を取得(  System.IO.Path.GetDirectoryName が簡単 )
		// **************************************************************
		String[] aDataDir = GetArray( md.FullyQualifiedName, @"\" );
		String pgDir = String.Join( @"\", aDataDir, 0, aDataDir.Length - 1 );

		return pgDir;

	}

}
このアーティクルの参照用URLをクリップボードにコピー メンテナンス
C# : CSVインポート & DB更新アプリ ( No.4 )
日時: 2007/07/21 20:18
名前: lightbox
拡張子:
using System.Data.Odbc;
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

// ********************************************************
// * 実行
// ********************************************************
public class App
{

	public static void Main() {

		DoAction myApp = new DoAction();

	}

}

public class DoAction
{

	public DoAction() {

		// ============================================
		// コンストラクタの呼び出し
		// ============================================
		lightbox lb = new lightbox(
			"Driver={MySQL ODBC 3.51 Driver};" +
			"SERVER=localhost;" +
			"DATABASE=mydb;" +
			"UID=root;" +
			"PWD=" );
	
		// ============================================
		// プログラムが存在するディレクトリを取得
		// ============================================
		String pgDir = lb.GetProgramDir();
		MessageBox.Show( pgDir );
	
		// ============================================
		// 変換したパスを初期ディレクトリとして設定
		// ============================================
		OpenFileDialog dlg = new OpenFileDialog();
		dlg.InitialDirectory = pgDir;
		dlg.Filter = "インポート用CSV|*.csv|全て|*.*";
		dlg.FilterIndex = 2;
		dlg.RestoreDirectory = true;
	
		// 列名保存用配列
		String[] aDataName = null;
		// データ名用配列
		String[] aDataValue = null;
		// ファイルの中身用
		Stream myStream = null;
		// SQL 作成用
		String str = "";
		// 存在チェック用
		String strQuery = "";
		// ============================================
		// ファイルを開くダイアログを表示
		// ============================================
		if ( dlg.ShowDialog() == DialogResult.OK ) {
			// ============================================
			// myStream としてファイルの中身を取得
			// ============================================
			myStream = dlg.OpenFile();
			if ( !(myStream == null) ) {
				// ============================================
				// DB 接続
				// ============================================
				if ( !lb.Connect() ) {
					myStream.Close();
					MessageBox.Show( "接続失敗の為、終了します   " );
					System.Environment.Exit( 0 );
				}
	
				// ============================================
				// myStream を読む為の StreamReader クラスを作成
				// ファイルは Shift_JIS なので明示する必要がある
				// ============================================
				StreamReader sr =
					new StreamReader(
						myStream,
						Encoding.GetEncoding("Shift_JIS")
					);
	
				// ============================================
				// ループ処理で行を結合して、SQL 文を作成
				// ============================================
				int nCounter = 0;
				int i = 0;
	
				while( sr.Peek() >= 0 ) {
					if ( nCounter == 0 ) {
						aDataName = lb.GetArray(sr.ReadLine(),",");
					}
					else {
						aDataValue = lb.GetArray(sr.ReadLine(),",");
	
						strQuery = "select * from 社員マスタ where ";
						strQuery += "社員コード = '" + aDataValue[0] + "'";
						if ( lb.ExistData( strQuery ) ) {
							// update 作成
							str = "update 社員マスタ set ";
							for( i = 0; i < aDataName.Length; i++ ) {
								// データ内のシングルクォートの処理
								aDataValue[i] = aDataValue[i].Replace("'", "''");
								if ( i != 0 ) {
									str += ",";
								}
								if ( i < 4 ) {
									str += aDataName[i];
									str += " = '";
									str += aDataValue[i];
									str += "'";
								}
								if ( i == 4 ) {
									str += aDataName[i];
									str += " = ";
									str += aDataValue[i];
								}
								if ( i > 4 ) {
									str += aDataName[i];
									str += " = '";
									str += aDataValue[i];
									str += "'";
								}
							}
							str += " where 社員コード = ";
							str += "'" + aDataValue[0] + "'";
						}
						else {
							// insert 作成
							str = "insert into 社員マスタ (";
							for( i = 0; i < aDataName.Length; i++ ) {
								if ( i != 0 ) {
									str += ",";
								}
								str += aDataName[i];
							}
							str += ") values(";
							for( i = 0; i < aDataName.Length; i++ ) {
								// データ内のシングルクォートの処理
								aDataValue[i] = aDataValue[i].Replace("'", "''");
								if ( i != 0 ) {
									str += ",";
								}
								if ( i < 4 ) {
									str += "'";
									str += aDataValue[i];
									str += "'";
								}
								if ( i == 4 ) {
									str += aDataValue[i];
								}
								if ( i > 4 ) {
									str += "'";
									str += aDataValue[i];
									str += "'";
								}
							}
							str += ")";
						}
	
						MessageBox.Show(str);
						lb.UpdateDB(str);
	
					}
					nCounter++;
	
				}
	
				// ============================================
				// リーダとストリームを閉じる
				// ============================================
				sr.Close();
				myStream.Close();
	
			}

			// ============================================
			// 接続解除
			// ============================================
			lb.Close();
		}

	}

}

// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// 処理クラス
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
public class lightbox
{

	// 接続オブジェクト
	private OdbcConnection myCon = new OdbcConnection();
	// コマンドオブジェクト
	private OdbcCommand myCommand = new OdbcCommand();
	// 接続文字列
	public String strCon = String.Empty;

	// ********************************************************
	// コンストラクタの定義( クラスと同名 )
	// ********************************************************
	public lightbox( String str ) {

		strCon = str;

	}

	// ********************************************************
	// 接続処理
	// ********************************************************
	public bool Connect() {

		bool bRet = true;

		// 接続文字列セット
		myCon.ConnectionString = strCon;

		// ====================================================
		// 例外処理
		// ====================================================
		try {
			// 接続
			myCon.Open();
		}
		catch( Exception ex ) {
			bRet = false;
			MessageBox.Show( ex.Message );
		}

		// コマンドオブジェクトを接続に関係付ける
		myCommand.Connection = myCon;

		return bRet;

	}

	// ********************************************************
	// 接続解除処理
	// ********************************************************
	public void Close() {

		myCon.Close();

	}

	// ********************************************************
	// 配列化関数
	// ********************************************************
	public String[] GetArray(String str,String d) {

		// 区切り文字定義
		String delimStr = d;
		Char[] delimiter = delimStr.ToCharArray();
		// 分解
		String[] aRet = str.Split(delimiter);

		return aRet;

	}

	// ********************************************************
	// 存在チェック
	// ********************************************************
	public bool ExistData(String strQuery) {

		OdbcDataReader myReader = null;
		bool bRet = true;

		// コマンドセット
		myCommand.CommandText = strQuery;

		// ====================================================
		// 例外処理
		// ====================================================
		try {
			// リーダーオブジェクト取得
			myReader = myCommand.ExecuteReader();
		}
		catch( Exception ex ) {
			myCon.Close();
			MessageBox.Show( ex.Message );
			System.Environment.Exit( 0 );
		}

		bRet = myReader.HasRows;
		myReader.Close();

		return bRet;

	}

	// ********************************************************
	// 更新関数
	// ********************************************************
	public bool UpdateDB(String strExec) {

		myCommand.CommandText = strExec;
		// ====================================================
		// 例外処理
		// ====================================================
		try {
			// 実行
			myCommand.ExecuteNonQuery();
		}
		catch( Exception ex ) {
			myCon.Close();
			MessageBox.Show( ex.Message );
			System.Environment.Exit( 0 );
		}

		return true;

	}

	// ********************************************************
	// プログラムが実行されているディレクトリを取得
	// ********************************************************
	public String GetProgramDir( ) {

		System.Reflection.Assembly ab = System.Reflection.Assembly.GetExecutingAssembly();
		System.Reflection.Module md = ab.GetModules()[0];
		// **************************************************************
		// ディレクトリ部分を取得(  System.IO.Path.GetDirectoryName が簡単 )
		// **************************************************************
		String[] aDataDir = GetArray( md.FullyQualifiedName, @"\" );
		String pgDir = String.Join( @"\", aDataDir, 0, aDataDir.Length - 1 );

		return pgDir;

	}

}
このアーティクルの参照用URLをクリップボードにコピー メンテナンス