使用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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)