怎么把sql的数据库封装成CDatabaseAccess类?

怎么把sql的数据库封装成CDatabaseAccess类?,第1张

可以参考一下这个:

使用CDatabase类来读取Microsoft Access数据,主要实现了以下功能:

从Microsoft Access 数据库读取数据

不使用ODBC数据源进行数据库连接

在List view控件中显示数据

// 以下是部分代码

void CReadDBDlg::OnRead()

{

// TODO: Add your control notification handler code here

CDatabase database

CString sSql

CString sCatID, sCategory

CString sDriver = "MICROSOFT ACCESS DRIVER (*.mdb)"

CString sDsn

CString sFile = "c:\\works\\ReadDB\\Test.mdb"// Change path here

int iRecord = 0

// Create a pseudo DSN including the name of the Driver and the Excel file

// so we donhave to have an explicit DSN installed in our ODBC admin

sDsn.Format("ODBCDRIVER={%s}DSN=''DBQ=%s",sDriver,sFile)

TRY

{

// Open the database

database.Open(NULL,false ,false ,sDsn)

// the recordset

CRecordset recset( &database )

// Build the SQL query string

sSql = "SELECT CatID, Category "

"FROM Categories"

// Execute the query)

recset.Open(CRecordset::forwardOnly,sSql,CRecordset::readOnly)

ResetListControl()

// Column heading

m_ListControl.InsertColumn(1,"Cat ID",LVCFMT_LEFT,30,0)

m_ListControl.InsertColumn(1,"Category",LVCFMT_LEFT,30,1)

// Browse the result

while ( !recset.IsEOF() )

{

// Read one record

recset.GetFieldValue("CatID",sCatID)

recset.GetFieldValue("Category",sCategory)

// Insert values into the list control

m_ListControl.InsertItem(0,sCatID,0)

m_ListControl.SetItemText(0,1,sCategory)

// goto next record

recset.MoveNext()

}

// Close the database

database.Close()

}

CATCH(CDBException, e)

{

// If a database exception occured, pop up error msg

AfxMessageBox("Database error: "+e->m_strError)

}

END_CATCH

}

void CReadDBDlg::ResetListControl()

{

m_ListControl.DeleteAllItems()

int iNbrOfColumns

CHeaderCtrl* pHeader = (CHeaderCtrl*)m_ListControl.GetDlgItem(0)

if (pHeader)

{

iNbrOfColumns = pHeader->GetItemCount()

}

for (int i = iNbrOfColumnsi >= 0i--)

{

m_ListControl.DeleteColumn(i)

}

}

1.web.config 中

<add key="ConnectionString" value="server=(local)uid=sapwd=123456database=News"/>

调用的时候

string strConn = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString()

SqlConnection Conn = new SqlConnection(strConn)

2.或者不用web.config直接在文件中写

SqlConnection conn = new SqlConnection("server=.\\SQLEXPRESSuid=sapwd=123456database=login")

如何是Express版的数据库,一定要在服务器名的后面加上 \\SSQLEXPRESS


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/6762965.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-27
下一篇 2023-03-27

发表评论

登录后才能评论

评论列表(0条)

保存