2015. 3. 4. 10:59

SQLite DB에다가 Adapter를 사용하여 DataTable을 Update 하려고 하니 DbType과 일치하는 실제 DB의 column type이 명확하지 않아  찾아보았더니 관련내용이 정리된 문서가 있어 공유합니다.


Since the SQLite engine is inherently typeless and ADO.NET is much more strongly typed, the ADO.NET wrapper must make certain decisions about the columns returned in any given SQL query.  One of the deciding factors is the underlying datatype declared in the CREATE TABLE statement.

The following lists the datatypes and mappings the SQLite ADO.NET wrapper understands.  If there is anything missing, wrong, or needs adding, please let me know:


COUNTERDbType.Int64
AUTOINCREMENTDbType.Int64
IDENTITYDbType.Int64
LONGDbType.Int64
TINYINTDbType.Byte
INTEGERDbType.Int64
INTDbType.Int32
VARCHARDbType.String
NVARCHARDbType.String
CHARDbType.String
TEXTDbType.String
DOUBLEDbType.Double
FLOATDbType.Double
REALDbType.Single
BITDbType.Boolean
YESNODbType.Boolean
LOGICALDbType.Boolean
BOOLDbType.Boolean
NUMERICDbType.Decimal
DECIMALDbType.Decimal
MONEYDbType.Decimal
CURRENCYDbType.Decimal
TIMEDbType.DateTime
DATEDbType.DateTime
TIMESTAMPDbType.DateTime
DATETIMEDbType.DateTime
BLOBDbType.Binary
BINARYDbType.Binary
VARBINARYDbType.Binary
IMAGEDbType.Binary
GENERALDbType.Binary
OLEOBJECTDbType.Binary
GUIDDbType.Guid
UNIQUEIDENTIFIERDbType.Guid
MEMODbType.String
NOTEDbType.String
LONGTEXTDbType.String
LONGCHARDbType.String
SMALLINTDbType.Int16
BIGINTDbType.Int64

DateTime's are stored in one of two formats.  The default datetime format is ISO8601, and you specify the format in the connection string like Finisar does.  The varying ISO8601 strings that this class uses to convert are:

"yyyy-MM-dd HH:mm:ss"

The other format is Ticks.  In the SQLiteConnection class in the helpfile is a description of all the connectionstring options.

,
"yyyyMMddHHmmss",
"yyyyMMddTHHmmssfffffff",
"yyyy-MM-dd",
"yy-MM-dd",
"yyyyMMdd",
"HH:mm:ss",
"THHmmss"


출처 : http://www.blogbus.com/hyangl-logs/2219450.html

Posted by 나이스곰
2012. 1. 25. 11:17
개발한 프로젝트에서 아주 희한한 버그가 보고되었는데, 64비트 윈도우즈7에서 폼을 띄우는(new 하는) 부분에서 죽어버리는 것이었다. (Access Violation)
일주일 내내 이 버그를 해결하기 위해 지지고 볶아봤지만 도무지 원인을 알 수가 없었다. 게다가 잘 되는 곳은 잘 되고 안 되는 곳은 안되는 형태였는데 딱히 시스템을 특정할 수 없어 엄청나게 고생했다.

결국 2주가 다 되어서야 간신히 원인을 찾게 되었는데 폼에서 MDB를 사용하는데 연결 시에 OLE DB Services 를 명시적으로 All Services(-1)로 주면 되는 것이었다. 명시하지 않으면 특정 x64 윈도우즈 시스템에서 뻗어버릴 수가 있다.

우리는 MS OFFICE가 원인일 것으로 보고 있다. 실제로 OFFICE 2010이 깔린 머신에서는 문제가 재현되지 않았기 때문이다. 물론, OFFICE 2007이 깔린 곳도 서비스팩과 핫픽스를 전부 받은 곳은 문제가 없는 것으로 보인다.

수정된 연결 문자열 예제 )


String.Format("Provider={0};Data Source={1};Jet OLEDB:Database Password={2};
OLE DB Services =-1;",
MdbProvider, MdbPath, MdbPassword));
Posted by 나이스곰
2011. 7. 18. 11:45

Path example
 

You will often need to extract parts of filename paths in your programs. The .NEW framework team at Microsoft has thought of this problem already and the Path class is ideal for our use. You can access it by adding "using System.IO;" at the top of your class. First here we see a short console program that shows four Path methods.
 

Program that uses Path methods [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
	string path = "C:\\stagelist.txt";

	string extension = Path.GetExtension(path);
	string filename = Path.GetFileName(path);
	string filenameNoExtension = Path.GetFileNameWithoutExtension(path);
	string root = Path.GetPathRoot(path);

	Console.WriteLine("{0}\n{1}\n{2}\n{3}",
	    extension,
	    filename,
	    filenameNoExtension,
	    root);
    }
}

Output

.txt
stagelist.txt
stagelist
C:\

 

출처 : http://www.dotnetperls.com/path
Posted by 나이스곰
2011. 6. 24. 11:03
여기서 얻어지는 rowID는 zero base 가 아니기 때문에 실제 접근시에 -1 해주어야 제대로 접근이 됩니다.
 
foreach(DataRow dataRow in foundRows)
{
System.Reflection.FieldInfo fieldInfo = dataRow.GetType().GetField("rowID",System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); 
int rowID = (int)fieldInfo.GetValue(dataRow);

this.dataGrid2.Select(rowID-1);
}

여기서 사용하는 Reflection 에는 유용한 기능들이 많으니 한번쯤 msdn을 둘러보시는 것도 좋을 것 같습니다.

출처 : http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/71ed2a79-5115-45f9-9ba4-fee80cfe9908/
Posted by 나이스곰
2011. 6. 14. 20:37

/* 2012년 8월 현재 구글 날씨 API 서비스가 지원되지 않기 때문에 이 프로그램은 정상적으로 동작하지 않습니다 */


.NET 의 LINQ 를 사용해보다가 심심해서 예제를 제작했습니다.
이전에 JAVA로 만들었던 기상정보 프로그램을 UI도 갖추고 해서 조금(?) 더 이쁘게 C#으로 만들었습니다.

(2012년 6월 25일 최종업데이트)


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Xml.Linq;


namespace LINQ

{

    public partial class LIQMain : Form

    {

        public class pair<T, U>

        {

            public pair() { }

            public pair(T First, U Second) { first = First; second = Second; }


            public T first { get; set; }

            public U second { get; set; }

        }


        protected List<pair<string, string>> m_cityList = new List<pair<string, string>>();

        

        public LIQMain()

        {

            InitializeComponent();


            LoadCities();


            getWeather(m_cityList[dropCities.SelectedIndex].first);

        }


        protected void LoadCities()

        {

            m_cityList.Add(new pair<string, string>("seoul", "서울"));

            m_cityList.Add(new pair<string, string>("incheon", "인천"));

            m_cityList.Add(new pair<string, string>("suwon", "수원"));

            m_cityList.Add(new pair<string, string>("osan", "오산"));

            m_cityList.Add(new pair<string, string>("hwaseong-si", "화성"));

            m_cityList.Add(new pair<string, string>("pyeongtaek", "평택"));

            m_cityList.Add(new pair<string, string>("yongin", "용인"));

            m_cityList.Add(new pair<string, string>("cheonan", "천안"));

            m_cityList.Add(new pair<string, string>("wonju", "원주"));

            m_cityList.Add(new pair<string, string>("chungju", "청주"));

            m_cityList.Add(new pair<string, string>("mokpo", "목포"));

            m_cityList.Add(new pair<string, string>("jeonju", "전주"));

            m_cityList.Add(new pair<string, string>("daegu", "대구"));

            m_cityList.Add(new pair<string, string>("gwangju", "광주"));

            m_cityList.Add(new pair<string, string>("pohang", "포항"));

            m_cityList.Add(new pair<string, string>("busan", "부산"));

            m_cityList.Add(new pair<string, string>("jeju", "제주"));


            foreach (pair<string, string> item in m_cityList)

            {

                dropCities.Items.Add(item.second);

            }


            dropCities.SelectedIndex = 0;

        }


        protected void getWeather(string strCity)

        {

            XDocument xmlDoc = XDocument.Load(String.Format("http://www.google.com/ig/api?weather={0}&ie=utf-8&oe=utf-8&hl=ko",strCity));


            var forcast_date = from weather in xmlDoc.Descendants("forecast_information")

                               select new

                               {

                                   date = weather.Element("forecast_date").Attribute("data").Value

                               };

         

            var weather_cast = from weather in xmlDoc.Descendants("current_conditions")

                            select new 

                            {

                                cur_weather = weather.Element("condition").Attribute("data").Value,

                                cur_temp_c = weather.Element("temp_c").Attribute("data").Value,

                                cur_humidity = weather.Element("humidity").Attribute("data").Value,

                                cur_wind = weather.Element("wind_condition").Attribute("data").Value,

                                cur_icon = weather.Element("icon").Attribute("data").Value

                            };


            var forecast = from foreweather in xmlDoc.Descendants("forecast_conditions")

                           select new

                           {

                               fore_day = foreweather.Element("day_of_week").Attribute("data").Value,

                               fore_low_temp = foreweather.Element("low").Attribute("data").Value,

                               fore_high_temp = foreweather.Element("high").Attribute("data").Value,

                               fore_weather = foreweather.Element("condition").Attribute("data").Value,

                               fore_icon = foreweather.Element("icon").Attribute("data").Value

                           };

            // 일기예보 일자

            if (forcast_date.Count() > 0)

            {

                string castDate = forcast_date.ElementAt(0).date;

                lblCastDate.Text = String.Format("일기예보 일자 : {0}", castDate.Replace('-', '.'));

            }

            else

                lblCastDate.Text = "-";

            // 현재 날씨

            if (weather_cast.Count() > 0)

            {

                weatherBox.Text = String.Format("{0}의 현재 날씨", m_cityList[dropCities.SelectedIndex].second);

                lblCWeather.Text = String.Format("{0}", weather_cast.ElementAt(0).cur_weather);

                lblCTemp.Text = String.Format("기온 : {0} ℃", weather_cast.ElementAt(0).cur_temp_c);

                lblCHumid.Text = String.Format("습도 : {0}",weather_cast.ElementAt(0).cur_humidity.Substring(weather_cast.ElementAt(0).cur_humidity.LastIndexOf(":")+1).Trim());

                lblCWind.Text = String.Format("풍향 : {0}",weather_cast.ElementAt(0).cur_wind.Substring(weather_cast.ElementAt(0).cur_wind.LastIndexOf(":")+1).Trim());


                try

                {

                    imgIcon.Load(String.Format("http://www.google.co.kr{0}",weather_cast.ElementAt(0).cur_icon));

                }

                catch (System.Exception)

                {


                }

            }

            // 내일 날씨

            if (forecast.Count() > 1)

            {

                foreBox.Text = String.Format("내일({0}) 날씨",forecast.ElementAt(1).fore_day);

                lblFWeather.Text = String.Format("{0}", forecast.ElementAt(1).fore_weather);

                lblFTempLow.Text = String.Format("최저 기온 : {0} ℃", forecast.ElementAt(1).fore_low_temp);

                lblFTempHigh.Text = String.Format("최고 기온 : {0} ℃", forecast.ElementAt(1).fore_high_temp);


                try

                {

                    imgFIcon.Load(String.Format("http://www.google.co.kr{0}", forecast.ElementAt(1).fore_icon));

                }

                catch (System.Exception)

                {


                }

            }

        }


        private void btnRefresh_Click(object sender, EventArgs e)

        {

            if (dropCities.SelectedIndex < 0)

                return;


            try

            {

                getWeather(m_cityList[dropCities.SelectedIndex].first);

            }

            catch (System.Exception ex)

            {

                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;

            }

        }

    }

}


001_기상정보.7z



Posted by 나이스곰
2011. 5. 24. 16:12

Programatically Set or Change DataRow's RowState

  The .NET Framework 2.0 adds a new feature: SetAdded, SetModified. You use this feature to set DataRow's RowState value programatically. This is applicable only when the current DataRow's RowState is Unchanged.

Simply use the following steps:


Make the necessary changes to the DataRow.


  Call AcceptChanges() for the DataRow. When invoking AcceptChanges, any DataRow object still in edit mode successfully ends its edit. Each DataRow's RowState property also changes; the Added and Modified rows become Unchanged,
and the Deleted rows are removed:

dsCopySess.Tables["DataTableName"].Rows[0].AcceptChanges();

Set the RowState as desired:

dsCopySess.Tables["DataTableName"].Rows[0].SetAdded();

요약하면 RowState 가 Unchanged 상태에서

아래처럼,
dsCopySess.Tables["DataTableName"].Rows[0].SetAdded();

데이터셋.테이블[인덱스].행[행번호].원하는 상태(SetAdded, SetModified....) 을 호출해주면 된다는 겁니다~


출처 : http://www.devx.com/tips/Tip/39112

Posted by 나이스곰
2011. 4. 28. 10:50


" 이 행은 이미 다른 테이블에 속해 있습니다 "

" This row already belongs to another table. "


DataRow 를 DataSet 에 잘못된 방법(기존 행을 바로 추가하는 방식 등)으로 추가하려는 경우 가끔 이런 문제가 생기는데
아래처럼 ItemArray 를 이용하면 해결된다.


DataRow row = table.rows[0];
dataset.Tables[0].Rows.Add(row.ItemArray);

Posted by 나이스곰
2011. 4. 3. 13:45

KeyValuePair<TKey, TValue> Structure

Defines a key/value pair that can be set or retrieved.

Type Parameters

TKey

The type of the key.

TValue

The type of the value.


이번에 처음으로 ASP.NET + C# 을 사용해서 프로젝트를 진행하면서 이런저런 어려움이 많습니다.
주 언어가 C++이다 보니 생각이 그 범위에서 완전히 벗어나기 어렵기도 하구요. ^-^;

여튼 C#에서 STL의 pair 와 같은 역할을 하는게 없나해서 찾아보니 KeyValuePair 가 있더군요.
사용법은 pair와 동일합니다.

MFC(C++) : std::pair<CString,CString>
C#            : KeyValuePair<string,string>

MFC(C++)

* 참고
foreach 문은 공식적으로 C++ 에서 지원되지 않습니다. 다만, Visual Studio Dev. Tool 에서 지원해주는 것입니다.
가끔 이걸 헷갈리시는 분들이 있더군요. 여기 예시에서는 편의를 위해 foreach를 사용했습니다.

for each( std::pair<CString,CString> kvp in myPairList)
{
    printf("Key = %s, Value = %s", kvp.first, kvp.second);
}

C#

foreach( KeyValuePair<string, string> kvp in myDictionary )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

더 자세한 내용은 msdn 을 참고하시면 되겠습니다.
http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx


* 직접 짜는 수고(?)를 덜기 위해 Stack Overflow 에 올라온 클래스를 같이 적어 놓습니다.

public class Pair<T, U> { 
   
public Pair() { 
   
} 
 
   
public Pair(T first, U second) { 
       
this.First = first; 
       
this.Second = second; 
   
} 
 
   
public T First { get; set; } 
   
public U Second { get; set; } 
}; 

출처 : http://stackoverflow.com/questions/166089/what-is-c-analog-of-c-stdpair
Posted by 나이스곰