寫數據庫之前最好先查看數據庫字段名是否存在,否則很容易出現(xiàn)寫數據庫失敗。
SqlConnection?^SqlServer_con; //SqlServer Form1(void) { InitializeComponent(); // //TODO:?在此處添加構造函數代碼 // this->SqlServer_con?=?gcnew?SqlConnection(); //this->SqlServer_con->ConnectionString?=?"server=(local);database=temp;uid=sa;pwd=!QAZ@WSX#EDC"; this->SqlServer_con->ConnectionString?=?"server=(local);database=test;uid=sa;pwd=123456"; try { this->SqlServer_con->Open(); } catch?(System::Exception^?e) { System::Windows::Forms::MessageBox::Show("鏈接數據庫失敗!",?"錯誤",?System::Windows::Forms::MessageBoxButtons::OK, System::Windows::Forms::MessageBoxIcon::Error); return; } SqlCommand?^SqlServer_cmd; //SqlServer SqlDataReader?^reader; try { SqlServer_cmd?=?gcnew?SqlCommand("SELECT?TOP?1?*?FROM?[sl651_2014]",?this->SqlServer_con); //SqlServer reader?=?SqlServer_cmd->ExecuteReader(); for?(int?i?=?0;?i?<?reader->FieldCount;i?++) { this->textBox1->Text?+=?""+(i+1)+"t"+reader->GetName(i)->ToString()+"rn"; } } catch?(System::Exception^?e) { } reader->Close(); this->SqlServer_con->Close(); }
使用 reader->GetName(i)即可獲取到指定列的字段名稱
reader->FieldCount即為列數量