首页 文章 精选 留言 我的

精选列表

搜索[c/c ],共10000篇文章
优秀的个人博客,低调大师

C++ Exercises(五)

问题:在窗体上画一个圆,并且可以用鼠标拖动它在窗体上运动到任何位置 分析: 一个圆是由它的外接矩阵决定的,而外接矩阵可以由矩阵的左上角点和矩阵的高度和宽度表示,这里显然要求外接矩阵的大小是不变的,变化的仅仅是外接矩阵的左上角点,所以要处理的就是矩阵左上角点的变化。 为此设置类的成员变量如下: CPoint m_pointTopLeft;//外接矩形左上角点 const CSize m_sizeEcllipse;//外接矩形大小 CSize m_sizeOffSet;//光标距离左上角点距离 bool m_bCaptured;//鼠标是否处于被捕获状态 其中矩阵大小是常量,在初始化的时候指明,这里我指定左上角点为坐标原点(0,0),高度100,宽度100,初始的鼠标光标和原点重合(即两者距离都是0),并且鼠标未被捕获。 CTestView::CTestView():m_sizeEcllipse(100,100),m_pointTopLeft(0,0),m_sizeOffSet(0,0) { this->m_bCaptured = FALSE;//初始状态为未捕获 } 接下来就是在OnDraw里面画圆了,因为m_pointTopLeft和m_sizeEcllipse已经唯一决定了圆的位置与大小,因此直接利用这两个变量进行绘图就可以了。 void CTestView::OnDraw(CDC* pDC) { CE05Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); CBrush brushHatch(HS_DIAGCROSS, RGB(255, 0, 0)); pDC->SelectObject(&brushHatch);//选择刷子 pDC->Ellipse(CRect(m_pointTopLeft, this->m_sizeEcllipse)); } 最后就是如何响应鼠标的三个事件:down,move,up了,再这里主要就是处理左上角点的变化,在down的时候,由于第一次点击圆内的点时就确定了鼠标光标与初始左上角点的距离,在以后的move中只需要用当前所在的point减去确定的m_sizeOffSet就可以确定此时的新左上角点,并且在move中利用前后两次的外接矩阵进行重画就可以了,最后在up中把鼠标的捕获释放掉。 void CTestView::OnLButtonDown(UINT nFlags, CPoint point) { CRect rt(this->m_pointTopLeft,this->m_sizeEcllipse); CRgn rg; CClientDC dc(this); OnPrepareDC(&dc); dc.LPtoDP(&rt);//转换到设备坐标 rg.CreateEllipticRgnIndirect(&rt); if(rg.PtInRegion(point)) {//在圆内单击左键了 this->SetCapture();//捕获光标 CPoint pointTopLeft(this->m_pointTopLeft);//前一次的左上角 this->m_sizeOffSet = point-pointTopLeft;//第一次点左键时光标距离左上角的距离 this->m_bCaptured = TRUE;//捕获标志设为true ::SetCursor(::LoadCursor(NULL,IDC_CROSS));//更改光标形状 } } void CTestView::OnLButtonUp(UINT nFlags, CPoint point) { if(this->m_bCaptured) {//光标处于捕获状态中 this->m_bCaptured = FALSE; //捕获标志设为false ::ReleaseCapture();//释放鼠标捕获 } } void CTestView::OnMouseMove(UINT nFlags, CPoint point) { if(this->m_bCaptured) {//光标处于捕获状态中 CClientDC dc(this); OnPrepareDC(&dc); CRect oldRect(this->m_pointTopLeft,this->m_sizeEcllipse);//老的外接矩形 dc.LPtoDP(&oldRect); this->InvalidateRect(&oldRect,TRUE);//强制重画 this->m_pointTopLeft = point-this->m_sizeOffSet;//新的左上角点 CRect newRect(this->m_pointTopLeft,this->m_sizeEcllipse);//新外接矩形 dc.LPtoDP(&newRect); this->InvalidateRect(&newRect,TRUE); //强制重画 } 本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2007/06/11/778954.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

C++ Exercises(十一)

1, #include <d3d9.h> #pragma warning( disable : 4996 ) // disable deprecated warning #include <strsafe.h> #pragma warning( default : 4996 ) //----------------------------------------------------------------------------- // Global variables //----------------------------------------------------------------------------- LPDIRECT3D9 g_pD3D = NULL; // Used to create the D3DDevice LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; // Our rendering device //----------------------------------------------------------------------------- // Name: InitD3D() // Desc: Initializes Direct3D //----------------------------------------------------------------------------- HRESULT InitD3D( HWND hWnd ) { // Create the D3D object, which is needed to create the D3DDevice. if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) ) return E_FAIL; // Set up the structure used to create the D3DDevice. Most parameters are // zeroed out. We set Windowed to TRUE, since we want to do D3D in a // window, and then set the SwapEffect to "discard", which is the most // efficient method of presenting the back buffer to the display. And // we request a back buffer format that matches the current desktop display // format. D3DPRESENT_PARAMETERS d3dpp; ZeroMemory( &d3dpp, sizeof(d3dpp) ); d3dpp.Windowed = TRUE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; // Create the Direct3D device. Here we are using the default adapter (most // systems only have one, unless they have multiple graphics hardware cards // installed) and requesting the HAL (which is saying we want the hardware // device rather than a software one). Software vertex processing is // specified since we know it will work on all cards. On cards that support // hardware vertex processing, though, we would see a big performance gain // by specifying hardware vertex processing. if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice ) ) ) { return E_FAIL; } // Device state would normally be set here return S_OK; } //----------------------------------------------------------------------------- // Name: Cleanup() // Desc: Releases all previously initialized objects //----------------------------------------------------------------------------- VOID Cleanup() { //释放D3D设备对象 if( g_pd3dDevice != NULL) g_pd3dDevice->Release(); //释放D3D对象 if( g_pD3D != NULL) g_pD3D->Release(); } //----------------------------------------------------------------------------- // Name: Render() // Desc: Draws the scene //----------------------------------------------------------------------------- VOID Render() { if( NULL == g_pd3dDevice ) return; // Clear the backbuffer to a blue color g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0 ); // Begin the scene if( SUCCEEDED( g_pd3dDevice->BeginScene() ) ) { // Rendering of scene objects can happen here // End the scene g_pd3dDevice->EndScene(); } // Present the backbuffer contents to the display g_pd3dDevice->Present( NULL, NULL, NULL, NULL ); } //----------------------------------------------------------------------------- // Name: MsgProc() // Desc: The window's message handler //----------------------------------------------------------------------------- LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: Cleanup(); PostQuitMessage( 0 ); return 0; case WM_PAINT: Render(); ValidateRect( hWnd, NULL ); return 0; } return DefWindowProc( hWnd, msg, wParam, lParam ); } //----------------------------------------------------------------------------- // Name: WinMain() // Desc: The application's entry point //----------------------------------------------------------------------------- INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT ) { // Register the window class WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, "D3D Tutorial", NULL }; RegisterClassEx( &wc ); // Create the application's window HWND hWnd = CreateWindow( "D3D Tutorial", "D3D Tutorial 01: CreateDevice", WS_OVERLAPPEDWINDOW, 100, 100, 300, 300, NULL, NULL, wc.hInstance, NULL ); // Initialize Direct3D if( SUCCEEDED( InitD3D( hWnd ) ) ) { //初始化成功 // Show the window ShowWindow( hWnd, SW_SHOWDEFAULT ); UpdateWindow( hWnd ); // Enter the message loop MSG msg; while(true) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) {//消息处理 if(msg.message==WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } else {//空闲时绘制 Render(); } } } UnregisterClass( "D3D Tutorial", wc.hInstance ); return 0; } 2, #include <d3d9.h> #pragma warning( disable : 4996 ) // disable deprecated warning #include <strsafe.h> #pragma warning( default : 4996 ) LPDIRECT3D9 g_pD3D = NULL; // Used to create the D3DDevice LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; // Our rendering device LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; // Buffer to hold vertices 顶点缓冲区 // A structure for our custom vertex type struct CUSTOMVERTEX { FLOAT x, y, z, rhw; // The transformed position for the vertex DWORD color; // The vertex color }; // Our custom FVF, which describes our custom vertex structure #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE) HRESULT InitD3D( HWND hWnd ) { // Create the D3D object. if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) ) return E_FAIL; // Set up the structure used to create the D3DDevice D3DPRESENT_PARAMETERS d3dpp; ZeroMemory( &d3dpp, sizeof(d3dpp) ); d3dpp.Windowed = TRUE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; // Create the D3DDevice if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &g_pd3dDevice ) ) ) { return E_FAIL; } // Device state would normally be set here return S_OK; } HRESULT InitVB() { // Initialize three vertices for rendering a triangle CUSTOMVERTEX vertices[] = { { 150.0f, 50.0f, 0.5f, 1.0f, 0xffff0000, }, // x, y, z, rhw, color { 250.0f, 250.0f, 0.5f, 1.0f, 0xff00ff00, }, { 50.0f, 250.0f, 0.5f, 1.0f, 0xff00ffff, }, }; // Create the vertex buffer. Here we are allocating enough memory // (from the default pool) to hold all our 3 custom vertices. We also // specify the FVF, so the vertex buffer knows what data it contains. if( FAILED( g_pd3dDevice->CreateVertexBuffer( 3*sizeof(CUSTOMVERTEX), 0, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL ) ) ) { return E_FAIL; } // Now we fill the vertex buffer. To do this, we need to Lock() the VB to // gain access to the vertices. This mechanism is required becuase vertex // buffers may be in device memory. VOID* pVertices; if( FAILED( g_pVB->Lock( 0, sizeof(vertices), (void**)&pVertices, 0 ) ) ) return E_FAIL; memcpy( pVertices, vertices, sizeof(vertices) ); g_pVB->Unlock(); return S_OK; } VOID Cleanup() { if( g_pVB != NULL ) g_pVB->Release(); if( g_pd3dDevice != NULL ) g_pd3dDevice->Release(); if( g_pD3D != NULL ) g_pD3D->Release(); } VOID Render() { // Clear the backbuffer to a blue color g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0 ); // Begin the scene if( SUCCEEDED( g_pd3dDevice->BeginScene() ) ) { // Draw the triangles in the vertex buffer. g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof(CUSTOMVERTEX) ); g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX ); g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 ); // End the scene g_pd3dDevice->EndScene(); } // Present the backbuffer contents to the display g_pd3dDevice->Present( NULL, NULL, NULL, NULL ); } LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: Cleanup(); PostQuitMessage( 0 ); return 0; } return DefWindowProc( hWnd, msg, wParam, lParam ); } INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT ) { // Register the window class WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, "D3D Tutorial", NULL }; RegisterClassEx( &wc ); // Create the application's window HWND hWnd = CreateWindow( "D3D Tutorial", "D3D Tutorial 01: CreateDevice", WS_OVERLAPPEDWINDOW, 100, 100, 300, 300, NULL, NULL, wc.hInstance, NULL ); // Initialize Direct3D if( SUCCEEDED( InitD3D( hWnd ) ) ) { //初始化成功 // Create the vertex buffer if( SUCCEEDED( InitVB() ) ) { // Show the window ShowWindow( hWnd, SW_SHOWDEFAULT ); UpdateWindow( hWnd ); // Enter the message loop MSG msg; while(true) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) {//消息处理 if(msg.message==WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } else {//空闲时绘制 Render(); } } } } UnregisterClass( "D3D Tutorial", wc.hInstance ); return 0; } 本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2008/04/26/1172475.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

C++ Exercises(七)

Dll的示例代码 namespace MathFuncs { class MyMathFuncs { public: // Returns a + b static __declspec(dllexport) double Add(double a, double b); // Returns a - b static __declspec(dllexport) double Subtract(double a, double b); // Returns a * b static __declspec(dllexport) double Multiply(double a, double b); // Returns a / b // Throws DivideByZeroException if b is 0 static __declspec(dllexport) double Divide(double a, double b); }; } #include "MathFuncsDll.h" #include <stdexcept> using namespace std; namespace MathFuncs { double MyMathFuncs::Add(double a, double b) { return a + b; } double MyMathFuncs::Subtract(double a, double b) { return a - b; } double MyMathFuncs::Multiply(double a, double b) { return a * b; } double MyMathFuncs::Divide(double a, double b) { if (b == 0) { throw new invalid_argument("b cannot be zero!"); } return a / b; } } // MyExecRefsDll.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "MathFuncsDll.h" #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { double a = 7.4; int b = 99; cout << "a + b = " << MathFuncs::MyMathFuncs::Add(a, b) << endl; cout << "a - b = " << MathFuncs::MyMathFuncs::Subtract(a, b) << endl; cout << "a * b = " << MathFuncs::MyMathFuncs::Multiply(a, b) << endl; cout << "a / b = " << MathFuncs::MyMathFuncs::Divide(a, b) << endl; cin>>a; return 0; } 本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2007/11/16/961857.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

C++ Exercises(八)

全排列问题: #include "stdafx.h" #include <math.h> #include <stdio.h> #include <iostream> using namespace std; void swap(int& a,int& b) { int tmp; tmp = a; a = b; b = tmp; } void Rerange(int a[],int m,int n) { if(m==n) { for(int j=0;j<=m;++j) cout<<a[j]<<'\t'; cout<<endl; } else { for(int i=m;i<=n;++i) { swap(a[m],a[i]); Rerange(a,m+1,n); swap(a[m],a[i]); } } } int main(void) { int a[] = {1,2,3},tmp; Rerange(a,0,2); cin>>tmp; return 0; } 本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2007/11/19/963829.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

C++ Exercises(一)

一个3D向量类 // Vertex3D.h: interface for the Vertex3D class. // ////////////////////////////////////////////////////////////////////// class Vertex3D {//3维向量类 private: double x,y,z; public: Vertex3D(); Vertex3D(double tx,double ty,double tz); Vertex3D(const Vertex3D& vt);//拷贝构造函数 Vertex3D& operator = (const Vertex3D &vt);//重载赋值运算符 bool operator == (const Vertex3D &vt)const;//重载"=="运算符 bool operator != (const Vertex3D &vt)const;//重载"!="运算符 Vertex3D operator -()const;//负向量 Vertex3D operator - (const Vertex3D &vt)const;//向量减法 Vertex3D operator + (const Vertex3D &vt)const;//向量加法 Vertex3D operator * (double fac)const;//与标量相乘 Vertex3D operator / (double fac)const;//与标量相除 Vertex3D& operator += (const Vertex3D &vt); Vertex3D& operator -= (const Vertex3D &vt); Vertex3D& operator *= (double fac);//与标量相乘 Vertex3D& operator /= (double fac);//与标量相除 double operator * (const Vertex3D &vt)const;//向量点乘 void reset(); void normalize();//向量单位化 double VertexLength()const;//向量模 virtual ~Vertex3D(); friend Vertex3D crossProduct(const Vertex3D &a,const Vertex3D &b); friend double Distance(const Vertex3D &a,const Vertex3D &b); }; // Vertex3D.cpp: implementation of the Vertex3D class. // ////////////////////////////////////////////////////////////////////// #include "Vertex3D.h" #include <math.h> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// Vertex3D::Vertex3D() { this->x = 0.0f; this->y = 0.0f; this->z = 0.0f; } Vertex3D::Vertex3D(double tx,double ty,double tz) { this->x = tx; this->y = ty; this->z = tz; } Vertex3D::Vertex3D(const Vertex3D &vt) { this->x = vt.x; this->y = vt.y; this->z = vt.z; } Vertex3D& Vertex3D::operator = (const Vertex3D& vt) { this->x = vt.x; this->y = vt.y; this->z = vt.z; return *this; } bool Vertex3D::operator == (const Vertex3D& vt)const {//判断向量是否相等 return this->x==vt.x&&this->y==vt.y&&this->z==vt.z; } bool Vertex3D::operator != (const Vertex3D& vt)const { return this->x!=vt.x&&this->y!=vt.y&&this->z!=vt.z; } Vertex3D Vertex3D::operator - ()const {//负向量 return Vertex3D(-x,-y,-z); } Vertex3D Vertex3D::operator - (const Vertex3D& vt)const {//向量减法 return Vertex3D(x-vt.x,y-vt.y,z-vt.z); } Vertex3D Vertex3D::operator + (const Vertex3D& vt)const {//向量加法 return Vertex3D(x+vt.x,y+vt.y,z+vt.z); } Vertex3D Vertex3D::operator * (double fac)const {//与标量乘法 return Vertex3D(x*fac,y*fac,z*fac); } Vertex3D Vertex3D::operator / (double fac)const {//与标量相除 return Vertex3D(x/fac,y/fac,z/fac); } Vertex3D& Vertex3D::operator += (const Vertex3D &vt) { this->x += vt.x; this->y += vt.y; this->z += vt.z; return *this; } Vertex3D& Vertex3D::operator -= (const Vertex3D &vt) { this->x -= vt.x; this->y -= vt.y; this->z -= vt.z; return *this; } Vertex3D& Vertex3D::operator *= (double fac) { this->x *= fac; this->y *= fac; this->z *= fac; return *this; } Vertex3D& Vertex3D::operator /= (double fac) { this->x /= fac; this->y /= fac; this->z /= fac; return *this; } void Vertex3D::reset() {//置为零向量 this->x = 0.0f; this->y = 0.0f; this->z = 0.0f; } double Vertex3D::VertexLength()const {//向量长度 double tmp = x*x+y*y+z*z; return sqrt(tmp); } void Vertex3D::normalize() {//向量单位化 double len = this->VertexLength();//获取向量长度 if(len>0.0f) { double tmp = 1.0f/len; this->x *= tmp; this->y *= tmp; this->z *= tmp; } } double Vertex3D::operator * (const Vertex3D &vt)const {//向量点乘 return x*vt.x+y*vt.y+z*vt.z; } Vertex3D::~Vertex3D() { } Vertex3D crossProduct(const Vertex3D &a,const Vertex3D &b) {//向量叉乘 return Vertex3D(a.y*b.z - a.z*b.y,a.z*b.x - a.x*b.z,a.x*b.y - a.y*b.x); } double Distance(const Vertex3D &a,const Vertex3D &b) {//向量距离 double dx = a.x - b.x,dy = a.y - b.y,dz = a.z - b.z; return sqrt(dx*dx+dy*dy+dz*dz); } 本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2007/04/29/732444.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

Objective-C SQLiteHelper

为毛要用CoreData,SQLite不是挺好吗? 如果你要用这些代码,请无比仔细测试。 欢迎各种拍砖、探讨! 你可以从这里下载 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 #import <Foundation/Foundation.h> typedef enum _db_op_result{ SUCCESSED= 0, FAILED = 1, CREATE_TABLE_FAILED = 5, TRANSACTION_EXE_FAILED = 7, UPDATE_FAILED = 9, DELETE_FAILED = 10, NOT_ALL_DONE = 20 } SMPDB_OPERATION_RESULT; typedef enum _db_op_type{ UPDATE = 1, DELETE = 2, INSERT = 3, } SMPDB_OPERTION_TYPE; @protocol DbOperationDelegate < NSObject > @optional - ( NSInteger )udpate; - ( NSInteger )insert; - ( NSInteger ) delete ; - ( NSArray *)select:( NSString *)condition; - ( NSString *)tableName; - ( NSString *)fieldsString; - ( NSString *)queryString; @end // SQLite Operation #import <Foundation/Foundation.h> #import "sqlite3.h" #import "DbOperationDelegate.h" @interface SMPDbUtil : NSObject { NSString *databasePath; sqlite3 *db; } @property ( readonly )sqlite3 *db; - ( NSInteger )createDatabase:( NSString *)dbName; - ( NSInteger )insert:( id <DbOperationDelegate>)obj; - ( NSInteger )insertSet:( NSString *)tableName tableFields:( NSArray *)fields valueSets:( NSArray *)values; - (sqlite3_stmt *)select:( id <DbOperationDelegate>)obj conditions:( NSString *)cons; - ( NSInteger )update:( id <DbOperationDelegate>)obj; @end //how to use #import <UIKit/UIKit.h> #import "DbOperationDelegate.h" @class ProvinceInfo; @interface CityInfo : NSObject <DbOperationDelegate>{ NSInteger cityId; NSString *cityName; ProvinceInfo *province; } @property (assign) NSInteger cityId; @property ( copy ) NSString *cityName; @property (retain)ProvinceInfo *province; - ( NSInteger )udpate; - ( NSInteger )insert; - ( NSInteger ) delete ; - ( NSArray *)select; - ( NSString *)fieldsString; - ( NSString *)queryString; @end //.m #import "CityInfo.h" #import "ProvinceInfo.h" #import "SMPDbUtil.h" #define TABLE_NAME @"city" @implementation CityInfo @synthesize cityId, cityName, province; - ( NSString *)tableName{ return @ "city" ; } - ( NSString *)fieldsString{ return @ " id, name, provinceId " ; } - ( NSString *)queryString{ return [ NSString stringWithFormat:@ "%d, \"%@\", %d" , self .cityId, self .cityName, (( self .province == nil ? -1 : self .province.provinceId))]; } - ( NSInteger )udpate{ SMPDbUtil *dbUtil = [[SMPDbUtil alloc]init]; NSInteger r = [dbUtil update: self ]; [dbUtil release]; return r; } - ( NSInteger )insert{ SMPDbUtil *dbUtil = [[SMPDbUtil alloc]init]; NSInteger r = [dbUtil insert: self ]; [dbUtil release]; return r; } //- (NSInteger)delete{ //return 0; //} - ( NSArray *)select:( NSString *)condition{ SMPDbUtil *dbUtil = [[SMPDbUtil alloc]init]; sqlite3_stmt *statement = [dbUtil select: self conditions:condition]; if (statement == NULL ) { sqlite3_close(dbUtil.db); return nil ; } NSMutableArray *array = [[[ NSMutableArray alloc]init]autorelease]; while (sqlite3_step(statement) == SQLITE_ROW) { CityInfo *el = [[CityInfo alloc]init]; NSInteger id = sqlite3_column_int(statement, 0); NSString *name = [[ NSString alloc] initWithUTF8String:( const char *) sqlite3_column_text(statement, 1)]; NSInteger provinceId = sqlite3_column_int(statement, 2); ProvinceInfo *p = [[ProvinceInfo alloc]init]; NSArray *proList = [p select:[ NSString stringWithFormat:@ "id = %d" , provinceId]]; if (proList != nil && proList.count > 0) { p = [proList objectAtIndex:0]; } el.cityId = id ; el.cityName = name; el.province = p; [array addObject:el]; [el release]; } sqlite3_close(dbUtil.db); [dbUtil release]; return array; } @end 欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 572064792 | Nodejs:329118122 做人要厚道,转载请注明出处! 本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sunshine-anycall/archive/2012/03/02/2377647.html ,如需转载请自行联系原作者

优秀的个人博客,低调大师

C++ 操作 Oracle

#include <string> #include <occi.h> #include <iostream> using namespace std; using namespace oracle::occi; struct Student_struct { int no; int age; string name; }; std::string getSQL(void) { std::string str_sql = "SELECT * FROM emp WHERE mgr=(:1)"; return str_sql; } /* 连接 Oracle 操作步骤 */ void connectOracle() { const string userName = "scott"; const string password = "tiger"; const string connString = "localhost:1521/orcl"; try { Environment *env = Environment::createEnvironment(Environment::DEFAULT); Connection *con = env->createConnection(userName, password, connString); cout << "Success to connect!" << endl; Statement *stmt = con->createStatement(); //动态 SQL stmt->setSQL("SELECT * FROM emp WHERE mgr=(:1) AND sal=(:2)"); stmt->setInt(1, 7902); stmt->setInt(2, 800); ResultSet *rs = stmt->executeQuery(); while (rs->next()) { int no = rs->getInt(1); string name = rs->getString(2); cout << "no is:" << no << endl; cout << "name :" << name << endl; cout << "MGR : "<<rs->getInt(4)<<endl; cout << "SAL :"<<rs->getInt(6)<<endl; } con->terminateStatement(stmt); env->terminateConnection(con); Environment::terminateEnvironment(env); } catch (SQLException &ex) { cout << ex.what() << endl; } system("pause"); } /* 增加 数据 */ void insertData(Connection *p_conn) { Statement *p_stmt = NULL; int m_no; string m_name; //string m_name; int m_age; int Flag = 0; //执行sql,返回结果并显示 cout << "PLEASE INPUT THE no! " << endl; for(;;) { fflush(stdin); if((!scanf_s("%d", &m_no)) || (m_no) < 0) { cout << "The no that you just input is invalid,please input it again !" << endl; continue; } else break; } string Verify_strsql( "select * from student where no =(:1)" ); p_stmt = p_conn->createStatement( Verify_strsql ); p_stmt->setInt(1, m_no); ResultSet *rset = p_stmt-> executeQuery(); /*while( rset->next() ) { Flag = rset->getInt(1); }*/ rset->next(); Flag = rset->getInt(1); if((m_no != 0) && (Flag != m_no)) /*判断是否为0或已经存在*/ { try { cout << "PLEASE INPUT THE name! " << endl; cin >> m_name; cout << "PLEASE INPUT THE age! " << endl; for(;;) { fflush(stdin); if((!scanf_s("%d", &m_age)) || (m_age) < 0) { cout << "The age that you just input is invalid,please input it again !!" << endl; continue; } else break; } string strsql = "insert into student (no,name,age) values (:1,:2,:3)"; p_stmt = p_conn->createStatement( strsql ); //p_stmt->setSQL(strsql); p_stmt->setInt(1, m_no); p_stmt->setString(2, m_name); p_stmt->setInt(3, m_age); cout << "The Statement that you input is " << strsql << endl; p_stmt-> executeUpdate(); p_conn->commit(); cout << "Successfully inserted a new record ! " << endl; } catch(SQLException *e) { cout << "exception: " << e->what() << endl; } p_conn->terminateStatement(p_stmt); } else { cout << "The user_no is invalid or has been exist!,please input it again!" << endl; } } /* 删除 数据 */ void deleteData(Connection *p_conn) { int m_no; int Flag = 0; Statement *p_stmt = NULL; //执行sql,返回结果并显示 //delete_data: cout << "Please input the number that you want to delete :" << endl; for(;;) { fflush(stdin); if(!scanf_s("%d", &m_no)) { cout << "输入字符出错!请重新输入!" << endl; continue; } else break; } string Verify_strsql( "select * from student where no =(:1)" ); p_stmt = p_conn->createStatement( Verify_strsql ); p_stmt->setInt(1, m_no); ResultSet *rset = p_stmt-> executeQuery(); /*while( rset->next() ) { Flag = rset->getInt(1); }*/ rset->next(); Flag = rset->getInt(1); if(Flag) { string strsql( "delete from student where no = (:1)"); p_stmt = p_conn->createStatement( strsql ); p_stmt->setInt(1, m_no); try { p_stmt-> executeUpdate(); p_conn->commit(); cout << "Successfully deleted an old record !" << endl; } catch(SQLException *e) { cout << "exception: " << e->what() << endl; } } else { cout << "The number that you just input didn't exist! please input a new number!" << endl; cout << "_____________________________________________________________________" << endl; //goto delete_data; } p_conn->terminateStatement(p_stmt); } /* 修改 数据 */ void setData(Connection *p_conn) { Statement *p_stmt = NULL; try { int m_no; int Flag = 0; string m_name; int m_age; cout << "Please input the number that you want to updata :" << endl; //cin>>m_no; for(;;) { fflush(stdin); if(!scanf_s("%d", &m_no)) { cout << "输入字符出错!请重新输入!" << endl; continue; } else break; } string Verify_strsql( "select * from student where no =(:1)" ); p_stmt = p_conn->createStatement( Verify_strsql ); p_stmt->setInt(1, m_no); ResultSet *rset = p_stmt-> executeQuery(); /*while( rset->next() ) { Flag = rset->getInt(1); }*/ rset->next(); Flag = rset->getInt(1); if(Flag) { cout << "PLEASE INPUT THE NEW name! " << endl; cin >> m_name; cout << "PLEASE INPUT THE NEW age! " << endl; //cin>>m_age; for(;;) { fflush(stdin); if((!scanf_s("%d", &m_age)) || (m_age) < 0) { cout << "The age that you just input is invalid,please input it again !!" << endl; continue; } else break; } string strsql = "update student set name=(:1),age=(:2) where no=(:3)"; p_stmt = p_conn->createStatement( strsql ); //p_stmt -> setSQL(strsql); int number = m_no; string name = m_name; int age = m_age; p_stmt->setInt(2, age); p_stmt->setString(1, name); p_stmt->setInt(3, number); p_stmt-> executeUpdate(); //cout <<"The Statement that you input is "<<strsql<< endl; cout << p_stmt->getSQL() << endl; p_conn->commit(); cout << " SUCCESSFULLY UPDATA A NEW RECORD !" << endl; } else { cout << "The number that you just input didn't exist!please input a new number!" << endl; cout << "_____________________________________________________________________" << endl; } } catch(SQLException *e) { cout << "exception: " << e->what() << endl; } p_conn->terminateStatement(p_stmt); } /* 查找 数据 */ void displayData(Connection *p_conn) { Statement *p_stmt = NULL; int row = 1; string strsql( "select * from student order by no" ); p_stmt = p_conn->createStatement( strsql ); ResultSet *rset = p_stmt-> executeQuery(); //查询语句 try { cout << setiosflags(ios::left) << setw(5) << "行号" << setiosflags(ios::left) << setw(5) << " 编号" << setiosflags(ios::left) << setw(8) << " 姓名" << setiosflags(ios::left) << setw(8) << " 年龄" << endl; while( rset->next() ) { int no = rset->getInt(1); int age = rset->getInt(3); string name = rset->getString(2); cout << "row." << setiosflags(ios::left) << setw(5) << row << " no=" << setiosflags(ios::left) << setw(5) << no << " name=" << setiosflags(ios::left) << setw(8) << name << " age=" << setiosflags(ios::left) << setw(10) << age << endl; row++; } } catch (SQLException *e) { cout << "exception: " << e->what() << endl; } p_stmt->closeResultSet(rset); p_conn->terminateStatement(p_stmt); } void findData(Connection *p_conn) { Statement *p_stmt = NULL; int no; int Flag = 0; cout << "Please input the number that you want to search :" << endl; //cin>> no; for(;;) { fflush(stdin); if(!scanf_s("%d", &no)) { cout << "输入字符出错!请重新输入!" << endl; continue; } else break; } string Verify_strsql( "select * from student where no =(:1)" ); p_stmt = p_conn->createStatement( Verify_strsql ); p_stmt->setInt(1, no); ResultSet *rset = p_stmt-> executeQuery(); /*while( rset->next() ) { Flag = rset->getInt(1); }*/ rset->next(); Flag = rset->getInt(1); if(Flag) { string strsql( "select * from student where no =(:1)" ); p_stmt = p_conn->createStatement( strsql ); p_stmt->setInt(1, no); ResultSet *rset = p_stmt-> executeQuery(); //查询语句 try { while( rset->next() ) { int no = rset->getInt(1); int age = rset->getInt(3); string name = rset->getString(2); cout << "no==" << no << " name==" << name << " age==" << age << endl; } } catch (SQLException *e) { cout << "exception: " << e->what() << endl; } } else { cout << "The data that you just input didn't exist! please input a new number!" << endl; cout << "___________________________________________________________________" << endl; } p_stmt->closeResultSet(rset); p_conn->terminateStatement(p_stmt); } void Export_data(Connection *p_conn) { unsigned int i = 0; Statement *p_stmt = NULL; Student_struct m_struct_student; vector<Student_struct> stu_strc; stu_strc.reserve(100); string strsql( "select * from student order by no" ); p_stmt = p_conn->createStatement( strsql ); ResultSet *rset = p_stmt-> executeQuery(); //查询语句 try { while( rset->next() ) { m_struct_student.no = rset->getInt(1); m_struct_student.age = rset->getInt(3); m_struct_student.name = rset->getString(2); stu_strc.push_back(m_struct_student); } /*vector<Student_struct>::iterator iter; iter = stu_strc.begin(); while(iter != stu_strc.end()) { cout<<*(iter++)<<endl; }*/ ofstream Vector_to_file("d:\\Database_file.txt"); if(!Vector_to_file) { cout << "error" << endl; return; } else { for(i = 0; i < stu_strc.size(); i++) { Vector_to_file << setiosflags(ios::left) << setw(8) << stu_strc[i].no << setiosflags(ios::left) << setw(8) << stu_strc[i].name << " " << setiosflags(ios::left) << setw(8) << stu_strc[i].age << endl; } Vector_to_file.close(); cout << "您已成功将以下数据写入d:\\Database_file.txt文件中 !" << endl; cout << endl; cout << setiosflags(ios::left) << setw(8) << "编号" << " " << setiosflags(ios::left) << setw(8) << "姓名" << " " << setiosflags(ios::left) << setw(8) << "年龄" << endl; for(i = 0; i < stu_strc.size(); i++) { cout << setiosflags(ios::left) << setw(8) << stu_strc[i].no << " " << setiosflags(ios::left) << setw(8) << stu_strc[i].name << " " << setiosflags(ios::left) << setw(8) << stu_strc[i].age << endl; } } //return EXIT_SUCCESS; } catch (SQLException *e) { cout << "exception: " << e->what() << endl; } p_stmt->closeResultSet(rset); p_conn->terminateStatement(p_stmt); } void Vector_save(Connection *p_conn) { Statement *p_stmt = NULL; Student_struct m_struct_student;//结构体变量 vector<Student_struct> stu_strc;//声明一个向量 stu_strc.reserve(100); string strsql( "select * from student order by no" ); p_stmt = p_conn->createStatement( strsql ); ResultSet *rset = p_stmt-> executeQuery(); //查询语句 try { while( rset->next() ) { m_struct_student.no = rset->getInt(1); m_struct_student.age = rset->getInt(3); m_struct_student.name = rset->getString(2); stu_strc.push_back(m_struct_student); } /*vector<Student_struct>::iterator iter; iter = stu_strc.begin(); while(iter != stu_strc.end()) { cout<<*(iter++)<<endl; }*/ cout << "您已成功将以下数据装入vector容器中 !" << endl; cout << endl; cout << setiosflags(ios::left) << setw(5) << "编号" << " " << setiosflags(ios::left) << setw(5) << "姓名" << " " << setiosflags(ios::left) << setw(5) << "年龄" << endl; for(unsigned int i = 0; i < stu_strc.size(); i++) { cout << setiosflags(ios::left) << setw(5) << stu_strc[i].no << " " << setiosflags(ios::left) << setw(5) << stu_strc[i].name << " " << setiosflags(ios::left) << setw(5) << stu_strc[i].age << endl; } } catch (SQLException *e) { cout << "exception: " << e->what() << endl; } p_stmt->closeResultSet(rset); p_conn->terminateStatement(p_stmt); } int main() { connectOracle(); return 0; }

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册