VC++でSQLへSELECT文を送り、エラーが発生した

このQ&Aのポイント
  • VC++でSQLへSELECT文を送りたいが、エラーが発生した。エラーメッセージは'ExecuteReader'が定義されていない識別子であり、printfの引数の型が一致しないというもの。
  • 開発環境はOSはXPのHomeEdition、Visual C++ ExpressEdition、SQL Server 2005 Express。
  • エラーを解決できる方法を教えて欲しい。
回答を見る
  • ベストアンサー

VC++でSQLへSELECT文を送ったのですが…

#include "stdafx.h" #include <stdio.h> #include <windows.h> #include <string> using namespace System; using namespace System::Data; using namespace System::Data::SqlClient; char a; int main(void) { String^ str; SqlConnection^ sqlConn = gcnew SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\○○\\test.mdf;Integrated Security=True;User Instance=True"); sqlConn->Open(); str = "Select test FROM Table1"; SqlCommand^ sqlCmd = gcnew SqlCommand(str,sqlConn);// SqlDataReader^ ExecuteReader (); sqlConn->Close(); } int sub() { a = ExecuteReader; printf (a,"表示テスト\n"); return 0; } の構文でSQL ServerへSELECT文を送り、そこで得た結果を 表示しようと思ったのですが 1>select-test.cpp 1>.\select-test.cpp(28) : error C2065: 'ExecuteReader' : 定義されていない識別子です。 1>.\select-test.cpp(29) : error C2664: 'printf' : 1 番目の引数を 'char' から 'const char *' に変換できません。 (新しい機能 ; ヘルプを参照) 1> 整数型からポインタ型への変換には reinterpret_cast、C スタイル キャストまたは 関数スタイル キャストが必要です。 と2つのエラーを返されてしまいました。 開発環境は OS XPのHomeEditon Visual C++ ExpressEdition SQL Server 2005 Express です。 よろしくお願いします。

質問者が選んだベストアンサー

  • ベストアンサー
  • redfox63
  • ベストアンサー率71% (1325/1856)
回答No.2

ごめんなさい ・・・ SqlCommandにExecuteはありませんね SqlDataReader^ exeReader = sqlCmd->ExecuteReader(); ですね subの呼び出しを sub( exeReader ); とします 関数sub側は void sub( SqlDataReader ^objRd ) {   // DBより取得したレコードを取得する   while( objRd->Read() ) {     Console::Writeln( L"{0}", objRd[0] );   } } といった具合にします C++/CLIでは printfより Console::WriteやWiltelnのほうが親和性がいいでしょう

yamatonbo
質問者

お礼

お返事ありがとうございます。 了解しました、さっそくやってみますね。

その他の回答 (1)

  • redfox63
  • ベストアンサー率71% (1325/1856)
回答No.1

関数subで ExecuteReaderを使いたいなら 引数に持たせるかグローバル変数にしましょう void sub( SqlDataReader^ objRd ) といった具合です SqlCommand^ sqlCmd = gcnew SqlCommand(str,sqlConn);// SqlDataReader^ ExecuteReader (); は SqlDataReader^ exeReader = sqlCmd->Execute(); といった具合でしょう printfに関するエラーは VC++2005以降はUnicedeが標準の文字セットになっています プロジェクト > プロパティの 構成プロパティ > 全般の 文字セットを『マルチバイト文字セットを使用する』に変更するか 文字列の前に Lをつけます printf( L"表示テスト\n" ); といった具合です printf( a, L"表示テスト\n" ); は何を期待しているコードでしょう aはSqlDataReaderのオブジェクトのように思います aのデータベースから取得したデータを表示したのであれば printf( L"表示テスト %s \n", a[0] ); などといった具合です … フィールド(列)の内容により %sは適宜修正してください

yamatonbo
質問者

お礼

すみません、まだ初心者なので、よく分からないところが何点か… 今、こんな形にしたのですが #include "stdafx.h" #include <stdio.h> #include <windows.h> #include <string> using namespace System; using namespace System::Data; using namespace System::Data::SqlClient; const wchar_t a=0; int main(void) { String^ str;//指令格納単語作成 SqlConnection^ sqlConn = gcnew SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\卒研\\test.mdf;Integrated Security=True;User Instance=True"); //↑接続先指定 sqlConn->Open();//サーバOPEN str = "Select test FROM Table1";//指令格納 SqlCommand^ sqlCmd = gcnew SqlCommand(str,sqlConn);// SqlDataReader^ exeReader = sqlCmd->Execute(); sqlConn->Close(); } void sub(SqlDataReader^ objRd) { a = ExecuteReader; printf( L"test\n",a ); return; } この構文でチャレンジしてみたところ 1>select-test.cpp 1>.\select-test.cpp(20) : error C2039: 'Execute' : 'System::Data::SqlClient::SqlCommand' のメンバではありません。 1> c:\windows\microsoft.net\framework\v2.0.50727\system.data.dll : 'System::Data::SqlClient::SqlCommand' の宣言を確認してください。 1>.\select-test.cpp(26) : error C2065: 'ExecuteReader' : 定義されていない識別子です。 1>.\select-test.cpp(27) : error C2664: 'printf' : 1 番目の引数を 'const wchar_t [6]' から 'const char *' に変換できません。(新しい 機能 ; ヘルプを参照) 1> 指示された型は関連がありません。変換には reinterpret_cast、C スタイル キャストまたは 関数スタイルのキャストが必要です。 と返されてしまいました。 あと、Executeについて調べると、ADOというものを見たのですが… access、というのでしょうか。 私のパソコンには入っていないので、初心者の偏見かもしれませんが どうやら使えない?のかな…と心配になっています…

関連するQ&A

  • VC++でSELECT文の実行結果を表示

    開発環境は OS XPのHomeEditon Visual C++ ExpressEdition SQL Server 2005 Express です。 よろしくお願いします。 #include "stdafx.h" #include <stdio.h> #include <windows.h> #include <string> using namespace System; using namespace System::Data; using namespace System::Data::SqlClient; char a; void sub( SqlDataReader ^objRd ) { System::Diagnostics::Debug::WriteLine(objRd); while( objRd->Read() ) { System::Diagnostics::Debug::WriteLine(objRd->Read()); } } int main(void){ String^ str; SqlConnection^ sqlConn = gcnew SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\SOUTUKEN\\TEST.mdf;Integrated Security=True;User Instance=True"); sqlConn->Open(); str = "SELECT * FROM table1"; SqlCommand^ sqlCmd = gcnew SqlCommand(str,sqlConn); SqlDataReader^ exeReader = sqlCmd->ExecuteReader(); sub( exeReader ); sqlConn->Close(); } これの実行結果がboolean形で帰ってくるのですがこれを表内のデータが帰ってくるようにしたいのです。 少し知識不足なところもありますがどうかよろしくお願いします。

  • 異なるソリューションの連結について教えてください。

    プログラミング初心者です。 開発環境 OS  XP HomeEdition Visual C++ Express Edition ソリューションAのCPPファイル #include "DxLib.h" int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { if( DxLib_Init() == -1 ) // DXライブラリ初期化処理 { return -1; // エラーが起きたら直ちに終了 } DxLib_End() ; // DXライブラリ使用の終了処理 return 0 ; // ソフトの終了 } ソリューションBのCPPファイル #include "stdafx.h" #include <stdio.h> #include <windows.h> #include <string> using namespace System; using namespace System::Data; using namespace System::Data::SqlClient; int main(void){ String^ str; SqlConnection^ sqlConn = gcnew SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\SOUTUKEN\\TEST.mdf;Integrated Security=True;User Instance=True"); sqlConn->Open(); str = "SELECT * FROM table1 "; //str= "INSERT INTO table1 (test) VALUES(3)"; SqlCommand^ sqlCmd = gcnew SqlCommand(str,sqlConn); SqlDataReader^ exeReader = sqlCmd->ExecuteReader(); while( exeReader->Read() ) { System::Diagnostics::Debug::WriteLine(exeReader["test"]->ToString()); } sqlConn->Close(); } です。ソリューション間の連結するのはどうしたらいいですか?

  • NULL値をSELECTする

    開発環境  Xp Home Edtion Microsoft Visual C++ 2008 Express Edition Microsoft SQL Server 2005 int i=0; String^ str1; sSqlConnection^ sqlConn = gcnew SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\SOUTUKEN\\test.mdf;Integrated Security=True;User Instance=True");qlConn->Open(); str1= "SELECT NoID FROM Table1 WHERE hentou IS NULL OR nyuryoku IS NULL"; sqlCommand^ sqlCmd=gcnew SqlCommand(str1,sqlConn); SqlDataReader^ exeReader=sqlCmd->ExecuteReader(); while(exeReader->Read()){ gyou[i]=exeReader[""]->ToString(); i++; } sqlConn->Close(); SELECT文でhentou,nyuryokuのどちらか一方でもNULLならばそのNoIDを取り出すということをしたいのですが、 "sqlCommandが定義されていない識別子です。"というエラーが出てきます。 SQL文が間違っていると思うのですがどのようにしたら良いのでしょうか何卒よろしくお願いします。

  • 文字列変換ついて

    開発環境  XP Home Edtion Microsoft Visual C++ 2008 Express Edition Microsoft SQL Server 2005 Express Edition Visual C++で入力フォームから数字の入力文字列でのInsert文を実行してそのまま反映させることはできたの ですが、日本語やアルファベットが入らないのですがどうしたらよいでしょうか? PSTR strText; String^ data; char *ree; ree=(char*)strText; String^ data; data=gcnew String(ree); SqlConnection^ sqlConn = gcnew SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\SOUTUKEN\\test.mdf;Integrated Security=True;User Instance=True"); sqlConn->Open(); str= "INSERT INTO table1 (test) VALUES("+data+")"; SqlCommand^ sqlCmd = gcnew SqlCommand(str,sqlConn); SqlDataReader^ exeReader = sqlCmd->ExecuteReader(); sqlConn->Close(); 何卒よろしくおねがいします。

  • 名前空間使用するには

    開発環境  XP Home Edition Microsoft Visual C++ 2008 Express Edition です。 #include "DxLib.h" #include <Windows.h> #include <string> #include <stdio.h> using namespace System; using namespace System::Data; using namespace System::Data::SqlClient; void in(){ String^ str; SqlConnection^ sqlConn = gcnew SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\SOUTUKEN\\TEST.mdf;Integrated Security=True;User Instance=True"); sqlConn->Open(); str = "SELECT * FROM table1 "; //str= "INSERT INTO table1 (test) VALUES(3)"; SqlCommand^ sqlCmd = gcnew SqlCommand(str,sqlConn); SqlDataReader^ exeReader = sqlCmd->ExecuteReader(); while( exeReader->Read() ) { Diagnostics::Debug::WriteLine(exeReader["test"]->ToString()); } Diagnostics::Debug::WriteLine( "表示テスト %s \n"); sqlConn->Close(); } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { if( DxLib_Init() == -1 ) // DXライブラリ初期化処理 { return -1; // エラーが起きたら直ちに終了 } DxLib_End() ; // DXライブラリ使用の終了処理 in(); return 0 ; // ソフトの終了 } プロジェクトのプロパティはDxライブラリの設定にしています。 http://homepage2.nifty.com/natupaji/DxLib/dxuse_vc2008express.html ここのサイトの通りにやっています。 知識不足なところもありますがお願いします。

  • テキストボックスに文字列を入れる

    開発環境 XP Home Edtion Microsoft Visual C++ 2008 Express Edition Microsoft SQL Server 2003 Express Edition SQL文で1から5までのNoIDを取得してそれをダイアログのテキストボックスIDC_XS1からIDC_XS5の場所に入れようとしています。 int i=1; String^ str; char* dstChar2; LPSTR dstLPSTR2; SqlConnection^ sqlConn = gcnew SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\SOUTUKEN\\test.mdf;Integrated Security=True;User Instance=True"); while(i<=5){ sqlConn->Open(); str= "SELECT * FROM Table1 WHERE NoID='"+i+"'"; SqlCommand^ sqlCmd = gcnew SqlCommand(str,sqlConn); SqlDataReader^ exeReader = sqlCmd->ExecuteReader(); while(exeReader->Read()){ str=exeReader["nyuryoku"]->ToString(); dstChar2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str); dstLPSTR2 = (LPCSTR)dstChar2; #define IDC_XS IDC_XS##i        //iの内容をIDC_XSに連結させたいのですがなかなかできないのです。 SetDlgItemText(hWnd,IDC_XS,dstLPSTR2); i++; } sqlConn->Close(); どのようにしたらテキストボックス5つの中にSQL文の結果が入るのでしょうか。何卒よろしくおねがいします。

  • 文字列の連結について

    開発環境 XP Home Edtion SQL Server2005 Express Edtion DBから選択してきたその値に .png という文字列を繋げて対応する画像を表示を反映させたいのですがどのようにすればよいですか? String^ str; SqlConnection^ sqlConn = gcnew SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\SOUTUKEN\\TEST.mdf;Integrated Security=True;User Instance=True"); sqlConn->Open(); str = "SELECT gazou FROM table1 WHERE gazou=1"; SqlCommand^ sqlCmd = gcnew SqlCommand(str,sqlConn); SqlDataReader^ exeReader = sqlCmd->ExecuteReader(); while(exeReader->Read() ) { str3=exeReader["gazou"]->ToString(); System::Diagnostics::Debug::WriteLine(str3); HDC hMdc; char* dstChar3; dstChar3 = (char*)(void*)Marshal::StringToHGlobalAnsi(str3); LPCSTR dstLPCSTR3; dstLPCSTR3 = (LPCSTR)dstChar3; LPCSTR name = "'"+dstLPCSTR3+"'.png"; HBITMAP hbmp = (HBITMAP)LoadImage( NULL, name, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION ); hMdc= CreateCompatibleDC(hdc ); SelectObject(hMdc, hbmp ); BitBlt(hdc, 0, 0, 2000, 5000, hMdc, 0, 0, SRCCOPY); DeleteDC(hMdc); DeleteObject(hbmp); } sqlConn->Close(); なにとぞよろしくお願いします。

  • VC++メッセージの送受信について教えてください。

    VC++でソフトを作成しています。 初心者なのでわからないことだらけです。 どなたかご教授お願いします。 ■環境 Windows xp mode Visual Studio 2010 Professional VC++ フォームアプリケーション .net Framework4.0 ■相談内容 アプリ1のtextBoxに入力された文字列をアプリ2に送信して、アプリ2のtextBoxに表示させたいのですが、PostMessageを使用するとメッセージが送れません。 また、SendMessageを使用すると送れますが、共有メモリを使用すると文字列が途中で途切れてしまいます。 PostMessageと共有メモリの使用は指令なのではずせません。 理由は送信側のアプリがロックされるのを防ぐため、後に多数のアプリから送信した文字列を取得できるようにするためです。 下記にソースコードを記載しますので、どこが悪いのか、何が原因でそうなるのか、どうすれば正常に動作するようにできるのかを教えてください。 特に、ソースについてはどこをどのように直せば良いかを教えていただけるとありがたいです。 ~送信側ソース~ #pragma once #include<windows.h> #include<iostream> #include<fstream> #include<string> #include<msclr/marshal.h> #pragma comment(lib,"user32.lib") int s; using namespace std; using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::Runtime::InteropServices; using namespace msclr::interop; [DllImport("user32.dll") ] extern System::String^ FindWindow(String^ lpClassName, String^ lpWindowName); [DllImport("user32.dll")] extern System::String^ PostMessage(HWND hWnd, int Msg, int wParam, int lParam); public: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { System::String^ moji_textBox4; moji_textBox4=textBox4->Text; s=textBox4->Text->Length+1; COPYDATASTRUCT cd; HWND hWnd; char buffer[500]; sprintf_s(&buffer[0],5,"%s",moji_textBox4); cd.dwData=0; cd.cbData=s;//strlen(buffer)+1; cd.lpData=buffer; hWnd=::FindWindow(nullptr,L"アプリ2"); ::PostMessage((HWND)hWnd,WM_COPYDATA,0,(LPARAM)&cd); ~受信側ソース~ #pragma once #pragma comment(lib,"user32.lib") #include<ctype.h> #include<windows.h> #include<msclr/marshal.h> using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::Runtime::InteropServices; using namespace msclr::interop; public: virtual void WndProc(System::Windows::Forms::Message% msg) override { if(msg.Msg== WM_COPYDATA) { COPYDATASTRUCT *cd; cd=(COPYDATASTRUCT *)msg.LParam.ToInt32(); System::String^ str; str=gcnew System::String((char *)cd->lpData); pin_ptr<const wchar_t>pstr=PtrToStringChars(str); System::String^ ShareMemoryName1=L"Information"; HANDLE hmap; char *pmap; marshal_context^ context= gcnew marshal_context; LPCTSTR ShareMemoryName2 = context->marshal_as<LPCTSTR>(ShareMemoryName1); hmap=::CreateFileMapping((HANDLE)0xFFFFFFFF,NULL,PAGE_READWRITE,0,2048, (LPCTSTR)ShareMemoryName2); pmap=(char *)::MapViewOfFile(hmap,FILE_MAP_ALL_ACCESS,0,0,1024); System::String^ pstr1= gcnew System::String(pstr); ZeroMemory(pmap,2048); memcpy_s(pmap,2048,pstr,sizeof(pstr)); System::String^ str1; str1= gcnew System::String((char *)pmap); textBox6->Text=str1; UnmapViewOfFile(pmap); CloseHandle(hmap); } Form::WndProc(msg); }

  • C#でのSQLへのアクセスについて

    SQL Serverのテーブルをコンソール上に表示する為のコードを書いたのですが SqlConnection SqlCommand SqlDataReader に対してエラーが出しまい、修正方法が分からず、どなたか教えて頂けないでしょうか? 【ソースコード】 using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using Microsoft.Data.SqlClient; static void Main(string[] args) { string connectionString = "Data Source=○○;Initial Catalog=○○;User ID=○○;Password=○○;"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand("SELECT * FROM [○○]", connection)) using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Console.WriteLine(reader["column1"]); Console.WriteLine(reader["column2"]); } } } }

  • gccでコンパイル時のエラー

    // test.cpp #include <stdio> using namespace std; int main(int argc, char *argv[]) { printf("test\n"); return 0; } 上記コードをコンパイルしたいのですが make -k g++ -g -O2 -Wall -I. -c test.cpp -o test.obj test.cpp:2:17: stdio: No such file or directory test.cpp: In function `int main(int, char**)': test.cpp:7: error: `printf' was not declared in this scope test.cpp:7: warning: unused variable 'printf' make: *** [test.obj] Error 1 make: Target `all' not remade because of errors. となります。 #include <stdio> using namespace std; を #include <stdio.h> // using namespace std; にすれば正常に終了するのですがなぜでしょうか? gccはMingw5.1.6からインストールしたもので、 バージョンはgcc3.4.5です。 Meadow上から実行しました。 回答よろしくお願い致します。