간단한 C# 디비연결....ㅎㅎㅎㅎ
ADO.NET
Contents
Object Model
기본 Data Access
C#
- 연결 설정
using System.Data;
using System.Data.SqlClient;
// ...
public void Openning()
{
string ConnectionString = "server=localhost;database=dbTest;uid=sa;pwd=sa";
SqlConnection Connect = new SqlConnection(ConnectionString);
Connect.Open();
Connect.Close();
}
- Update
// ExecuteNonQuery
public void Updating()
{
string ConnectionString = "server=localhost;database=dbTest;uid=sa;pwd=sa";
SqlConnection Connect = new SqlConnection(ConnectionString);
string strInsertSQL = "Insert Into tblTest( Id, col2) Values(1,11)";
SqlCommand Command = new SqlCommand(strInsertSQL, Connect);
Connect.Open();
Command.ExecuteNonQuery();
Connect.Close();
}
- Query 1
// ExecuteScalar
public void Quering1()
{
string ConnectionString = "server=localhost;database=dbTest;uid=sa;pwd=sa";
SqlConnection Connect = new SqlConnection(ConnectionString);
string strSelectSQL = "Select count(tblTest.Id) From tblTest";
SqlCommand Command = new SqlCommand(strSelectSQL, Connect);
Connect.Open();
int count = (int)Command.ExecuteScalar();
Connect.Close();
// ...
}
- Query 2
// ExecuteReader // forward-only stream
public void Quering2()
{
string ConnectionString = "server=localhost;database=dbTest;uid=sa;pwd=sa";
SqlConnection Connect = new SqlConnection(ConnectionString);
string strSelectSQL = "Select tblTest.Id, tblTest.col2 From tblTest";
SqlCommand Command = new SqlCommand(strSelectSQL, Connect);
Connect.Open();
SqlDataReader Reader= Command.ExecuteReader();// forward-only stream
while(Reader.Read())
{
string strId = Reader["Id"].ToString();
string strcol2 = Reader["col2"].ToString();
Console.WriteLine("{0}:{1}", strId, strcol2);
}
Connect.Close();
}
- 예외 처리
- 기타
DataSet 과 DataAdapter
- 비 연결성 Data 조작 제공
- Query 3
// SqlDataAdapter & DataSet
public void Quering3()
{
string ConnectionString = "server=localhost;database=dbTest;uid=sa;pwd=sa";
SqlConnection Connect = new SqlConnection(ConnectionString);
string strSelectSQL = "Select tblTest.Id, tblTest.col2 From tblTest";
SqlCommand Command = new SqlCommand(strSelectSQL, Connect);
DataSet ds = new DataSet();
SqlDataAdapter aDataAdapter = new SqlDataAdapter(strSelectSQL,Connect);
Connect.Open();
aDataAdapter.Fill(ds);
Connect.Close();
foreach(DataTable aTable in ds.Tables)
{
foreach(DataRow aRow in aTable.Rows)
{
string strId = aRow["Id"].ToString().Trim();
string strcol2 = aRow["col2"].ToString().Trim();
Console.WriteLine("{0}:{1}", strId, strcol2);
}
}
}