visual c++ 2015 使用ado.net例程, 向数据库表插入一行并查询行数。

数据库名为:test 

表名为: idvalues, 有两个字段:id int, name varchar(50)


代码在visual c++ 2015 下编辑通过。

#include

#include
#include "stdafx.h"

#using

#using
#using


using namespace System;
using namespace System::Data;
using namespace System::Data::Common;
using namespace System::Data::SqlClient;


int main()
{
System::Console::Write("begin\n");
SqlConnection ^conn = gcnew SqlConnection();
conn->ConnectionString = L"data source=(local);integrated security=true;initial catalog=test;";
try {
conn->Open();
}
catch (SqlException ^ex) {
System::Console::Write("Error:"+ex->Message+"\n");
goto error;
}
SqlCommand ^cmd = gcnew SqlCommand();
cmd->CommandType = CommandType::Text;
cmd->Connection = conn;
cmd->CommandText = "Declare @id int; SELECT @id=MAX(ID) FROM idValues; INSERT INTO idValues(id, name)VALUES(ISNULL(@id,0)+1, 'name'+CAST(@id as varchar(12)))";
int rows =cmd->ExecuteNonQuery();
System::Console::WriteLine("affected Rows: "+ rows.ToString());


cmd->CommandText = L"select count(1) from idValues";
Object ^o = cmd->ExecuteScalar();
System::Console::WriteLine("idValues has "+ o->ToString() + " rows now.");


System::Console::WriteLine("end");
goto exitor;
error:
exitor:
System::Console::Read();
conn->Close();
delete conn;
delete cmd;
    return 0;
}

你可能感兴趣的:(ado.net,vc++2015,数据库操作)