아무도 안해서 ㅡㅡ; 다 취소~ public static int ExecuteNonQuery(SqlConnection connection, string commandText, if (commandParameters != null) int result = cmd.ExecuteNonQuery(); return result;
사용 하는거 발표 ;;
return 값에 따른 MssqlHelper
params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = commandText;
cmd.CommandType = CommandType.Text;
foreach (SqlParameter p in commandParameters)
cmd.Parameters.Add(p);
cmd.Parameters.Clear();
}
1. 숫자 : 조회 Count
2. DataSet : 데이터
3. XML : 데이터
4. DataRow : 데이터
5. MsSqlDataReader : 데이터
6. object
7. 특정 class
8. 특정 Collection
위의 방식 외 여러가지 상황이 있겠지만 대략 이렇게 생각 해 봤습니다.
'분류 전체보기'에 해당되는 글 159건
- 2009.02.24 발표 정리 3회
- 2009.02.24 MSSQL Helper #4
- 2009.02.21 Tip) 상속에 대한 Method 사용 관련 정리..
- 2009.02.21 (1) class, inheritance, [abstract], interface 개념 잡기 #2
- 2009.02.17 (1) class, [inheritance], abstract, interface 개념 잡기 #2
- 2009.02.16 (1) [class], inheritance, abstract, interface 개념 잡기 #1
- 2009.01.23 delegate callback
- 2009.01.23 Delegate 비동기 #2
- 2009.01.23 Delegate 비동기화 사용
- 2008.12.10 C# API 사용하기 #2
/// <summary>
/// Execute a single command against a MySQL database.
/// </summary>
/// <param name="connectionString">Settings to use for the update</param>
/// <param name="commandText">Command text to use for the update</param>
/// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
public static object ExecuteScalar(string connectionString, string commandText)
{
//pass through the call providing null for the set of MySqlParameters
return ExecuteScalar(connectionString, commandText, (MySqlParameter[])null);
}
/// <summary>
/// Execute a single command against a MySQL database.
/// </summary>
/// <param name="connectionString">Settings to use for the command</param>
/// <param name="commandText">Command text to use for the command</param>
/// <param name="commandParameters">Parameters to use for the command</param>
/// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
public static object ExecuteScalar(string connectionString, string commandText, params MySqlParameter[] commandParameters)
{
//create & open a SqlConnection, and dispose of it after we are done.
using (MySqlConnection cn = new MySqlConnection(connectionString))
{
cn.Open();
//call the overload that takes a connection in place of the connection string
return ExecuteScalar(cn, commandText, commandParameters);
}
}
/// <summary>
/// Execute a single command against a MySQL database.
/// </summary>
/// <param name="connection"><see cref="MySqlConnection"/> object to use</param>
/// <param name="commandText">Command text to use for the command</param>
/// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
public static object ExecuteScalar(MySqlConnection connection, string commandText)
{
//pass through the call providing null for the set of MySqlParameters
return ExecuteScalar(connection, commandText, (MySqlParameter[])null);
}
/// <summary>
/// Execute a single command against a MySQL database.
/// </summary>
/// <param name="connection"><see cref="MySqlConnection"/> object to use</param>
/// <param name="commandText">Command text to use for the command</param>
/// <param name="commandParameters">Parameters to use for the command</param>
/// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
public static object ExecuteScalar(MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters)
{
//create a command and prepare it for execution
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connection;
cmd.CommandText = commandText;
cmd.CommandType = CommandType.Text;
if (commandParameters != null)
foreach (MySqlParameter p in commandParameters)
cmd.Parameters.Add( p );
//execute the command & return the results
object retval = cmd.ExecuteScalar();
// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
return retval;
}
#endregion
}
}
http://www.koders.com/csharp/fid01EA450A209966FCB52CA84DABB208DEF807D142.aspx
using System; namespace InheritanceMethodExam public virtual void BteamInfo() //virtual 은 상속 받는 class에서 변경 하겠다 선언 |
using System; namespace InheritanceMethod2 |
: 예를 들어 나는 말을 한다. 하지만 말은 하지만 어떤 말을 할 지는 알 수 없다.
이런 명확하지 않지만 반드시 하는 것을 정의 할때 추상화 class를 사용 합니다.
(개인적으로 생각 하는 개념 )
[형식]
지정자 abstract class 이름 : 기반 abstract { // 멤버 목록 } |
using System; namespace AbstractExam public class Ok public class B : A class Program ok.Display(); |
: 특정 class의 모든 멤버를 물려 받는 것을 말합니다.
(메소드, 필드, 해당 class에 선언된 모든 부분)
[형식]
protected class 기반class { // 멤버 목록 } 지정자 class 이름 : 기반 class { //멤버 목록 } |
[알아두어야 할 사항]
public, protected .. 의 지정자 class로 설정 해야 해당 class의 멤버들을 사용 할 수 있습니다.
sealed 의 지정자는 상속 할 수 없습니다.
상속 class 사용 예제 (winform)
using System; namespace InheritanceExam |
(함수, 변수, 상수등 모든 것이 클래스 소속 되어야 함)
[형식]
지정자 class 이름 : 기반 class { // 멤버 목록 } |
1. public class A {} 외부에서 마음대로 Access 할 수 있습니다. |
2. private class A {} 내부에서만 Access 할 수 있습니다. |
3. protected class A {} 내부 혹은 상속 받을 때만 Access 할 수 있 습니다. |
4. sealed class A {} 상속 할 수 없는 class 입니다. |
5. partial class A {} partial 을 사용 하고 class 이름이 같을 경우 동일한 class로 인식 합니다. |
기본 Class 사용 방법
using System; namespace Study1 class BTeam userName = new Dictionary<int, string>(); return userName; foreach (KeyValuePair<int,string> KeyPrint in a) } |
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
public class MainClass
{
public static void Method(string strValue_1, ref string strValue_2, int time)
{
TestAsyncClass tac = new TestAsyncClass();
TestAsyncDelegate tad = new TestAsyncDelegate(tac.AsyncMethod);
TestAsyncWrapper taw = new TestAsyncWrapper(strValue_1, strValue_2);
AsyncCallback cb = new AsyncCallback(taw.Results);
IAsyncResult ar = tad.BeginInvoke(strValue_1, ref strValue_2, cb, null);
for(int i=0; i<5; i++)
{
Console.WriteLine("다른일을 처리합니다.");
Thread.Sleep(time);
}
while(true)
{
if(ar.IsCompleted) break;
Console.WriteLine("처리가 끝날때까지 기다립니다.");
Thread.Sleep(1000);
}
}
public static void Main(String[] args)
{
string Value = "World";
Console.WriteLine("============= 첫번째 동작 =============");
Method("Hello", ref Value, 500);
Console.WriteLine("============= 두번째 동작 =============");
Method("Thank you", ref Value, 2000);
}
}
public class TestAsyncClass
{
public int AsyncMethod(string strValue_1, ref string strValue_2)
{
Thread.Sleep(5000);
strValue_2 = strValue_1;
return strValue_1.Length + strValue_2.Length;
}
}
public delegate int TestAsyncDelegate(string strValue_1, ref string strValue_2);
public class TestAsyncWrapper
{
private string m_strValue_1;
private string m_strValue_2;
public TestAsyncWrapper(string strValue_1, string strValue_2)
{
m_strValue_1 = strValue_1;
m_strValue_2 = strValue_2;
}
[OneWayAttribute()]
public void Results(IAsyncResult ar)
{
int retVal;
string retStr = "";
TestAsyncDelegate tad = (TestAsyncDelegate)((AsyncResult)ar).AsyncDelegate;
retVal = tad.EndInvoke(ref retStr, ar);
Console.WriteLine("문자의 갯수 : {0}, 반환문자열 : {1}", retVal, retStr);
}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Specialized;
using System.Collections;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class UseDelegateForAsyncCallback
{
static int requestCounter;
static ArrayList hostData = new ArrayList();
static StringCollection hostNames = new StringCollection();
static void UpdateUserInterface()
{
// Print a message to indicate that the application
// is still working on the remaining requests.
Console.WriteLine("{0} requests remaining.", requestCounter);
}
public static void Main()
{
// Create the delegate that will process the results of the
// asynchronous request.
AsyncCallback callBack = new AsyncCallback(ProcessDnsInformation);
string host;
do
{
Console.Write(" Enter the name of a host computer or <enter> to finish: ");
host = Console.ReadLine();
if (host.Length > 0)
{
Interlocked.Increment(ref requestCounter);
Dns.BeginGetHostEntry(host, callBack, host);
}
} while (host.Length > 0);
// The user has entered all of the host names for lookup.
// Now wait until the threads complete.
while (requestCounter > 0)
{
UpdateUserInterface();
}
// Display the results.
for (int i = 0; i< hostNames.Count; i++)
{
object data = hostData [i];
string message = data as string;
// A SocketException was thrown.
if (message != null)
{
Console.WriteLine("Request for {0} returned message: {1}",
hostNames[i], message);
continue;
}
// Get the results.
IPHostEntry h = (IPHostEntry) data;
string[] aliases = h.Aliases;
IPAddress[] addresses = h.AddressList;
if (aliases.Length > 0)
{
Console.WriteLine("Aliases for {0}", hostNames[i]);
for (int j = 0; j < aliases.Length; j++)
{
Console.WriteLine("{0}", aliases[j]);
}
}
if (addresses.Length > 0)
{
Console.WriteLine("Addresses for {0}", hostNames[i]);
for (int k = 0; k < addresses.Length; k++)
{
Console.WriteLine("{0}",addresses[k].ToString());
}
}
}
}
static void ProcessDnsInformation(IAsyncResult result)
{
string hostName = (string) result.AsyncState;
hostNames.Add(hostName);
try
{
IPHostEntry host = Dns.EndGetHostEntry(result);
hostData.Add(host);
}
catch (SocketException e)
{
hostData.Add(e.Message);
}
finally
{
Interlocked.Decrement(ref requestCounter);
}
}
}
}
using System;
using System.Threading;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncDemo
{
// The method to be executed asynchronously.
public string TestMethod(int callDuration, out int threadId)
{
Console.WriteLine("Test method begins.");
Thread.Sleep(callDuration);
threadId = Thread.CurrentThread.ManagedThreadId;
return String.Format("My call time was {0}.", callDuration.ToString());
}
}
// The delegate must have the same signature as the method
// it will call asynchronously.
public delegate string AsyncMethodCaller(int callDuration, out int threadId);
}
...
using System;
using System.Threading;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncMain
{
static void Main()
{
// The asynchronous method puts the thread id here.
int threadId;
// Create an instance of the test class.
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
// Initiate the asychronous call.
IAsyncResult result = caller.BeginInvoke(3000,
out threadId, null, null);
Thread.Sleep(0);
Console.WriteLine("Main thread {0} does some work.",
Thread.CurrentThread.ManagedThreadId);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
// Perform additional processing here.
// Call EndInvoke to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, result);
// Close the wait handle.
result.AsyncWaitHandle.Close();
Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
}
}
/* This example produces output similar to the following:
Main thread 1 does some work.
Test method begins.
The call executed on thread 3, with return value "My call time was 3000.".
*/
C#에서 Win32 API 사용하기
개요
Win32 API를 불러올 때, 함수의 명칭, 인자, 리턴 값을 가지고 불러오게 되어 있다. 하지만, C#에서 타입들이 모두 객체(Object)의 형식이며, 일반적인 C 의 데이터 형과 상이한 모양을 가진다. 이러한 문제들을 해결할 수 있는 것이 PInvoke 기능이다.
PInvoke( Platform Invocation Service)는 관리화 코드에서 비관리화 코드를 호출할 방법을 제공한다. 일반적인 용도는 Win32 API의 호출을 위해 사용한다.
namespace PinvokeExample { using System; using System.Runtime.InteropServices; // 반드시 입력해야 한다. public class Win32 { [DllImport(“user32.dll”)] public static extern int FindWindow(string a, string b); … } } |
위 예제는 FindWindow라는 user32.dll의 C함수를 사용하는 모습을 보여주고 있다. 실제 FindWindow의 선언은 다음과 같다.
HWND FindWindow(LPCSTR swClassName, LPCSTR swTitle); |
HWND는 윈도우 핸들을 표현하는 32비트 정수 이므로, int형으로 치환되고 LPCSTR 형은 NULL로 끝나는 문자열을 표현한다. 이때 PInvoke는 string을 자동으로 LPCSTR로 치환해 주는 역할을 하게 된다.
이 문서에서는 이처럼 Win32 API 함수의 여러 유형들을 어떻게 C#에서 사용 할 것인지에 대하여 알아보자.