日期:2014-05-18  浏览次数:20492 次

跪求:一个超级简单的SQL应用程序?详情请看贴
本人初学数据库,现要完成一个小程序,大概如下:
        编写一个应用程序,对数据库中的某个表进行插入记录动作,如果满足完整性约束,操作成功,则输出数字“1”,如果不满足完整性约束,则输出数字“0”。
        本人不知道如何在应用程序操纵数据库中数据,做好用ODBC!不过其他方法也可以,请诸位高手,提供代码,谢谢!

------解决方案--------------------
这是我的C#程序里的一段snippet, 你看看能不能用一用.

// let 's insert the record in the table
sqlString = string.Format( "INSERT INTO MyTable (ID, Name) VALUES ({0}, {1}) ", data1.id, p0.name);
int rw = Database.ExecNonQuery(sqlString);
if (rw != 1)
throw (new ApplicationException(string.Format( "cannot insert the record into MyTable with id = {0} ", data1.id)));

其中Database类的定义如下:
public class Database
{
public static string ConnectString = "server=192.168.1.100;database=MyDatabase;uid=UserName;pwd=Password; ";

#region Execute Functions
static int Execute(SqlCommand comm)
{
SqlConnection connection = new SqlConnection(ConnectString);

int rv = 0;

try
{
connection.Open();
comm.Connection = connection;

rv = comm.ExecuteNonQuery();
}
catch
{
rv = -1;
}

connection.Close();
return rv;
}

static public int ExecNonQuery(string sql)
{
SqlCommand c = new SqlCommand(sql);
c.CommandType = CommandType.Text;

return Execute(c);
}

}


------解决方案--------------------
试试这个, 至少在我的VS2005上是work的。

#include <string>
#include <windows.h>
#include <stddef.h>
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>

int main()
{

wchar_t* connectString = L "Driver={SQL Server};Server=Cobra;Database=TestData;Uid=User;Pwd=password; ";

std::wstring cs = connectString;
HENV henv2;
HDBC hdbc2;
RETCODE retcode2;

short int ldbconn2, lout2;
wchar_t outconnect2[1024];

SQLAllocEnv(&henv2);
SQLAllocConnect(henv2, &hdbc2);

retcode2 = SQLSetConnectOption(hdbc2, SQL_ODBC_CURSORS, SQL_CUR_USE_ODBC);
ldbconn2 = cs.size();
retcode2 = SQLDriverConnect(hdbc2, NULL, connectString, ldbconn2, outconnect2, 1024, &lout2, SQL_DRIVER_NOPROMPT);
if(retcode2 != SQL_SUCCESS && retcode2 != SQL_SUCCESS_WITH_INFO)
{
printf( "Unable to connect DB = %s\n ", connectString);
return -1;
}

wchar_t* SQLstring = L "Insert into TF_Test (ID, Name) Values(1, 'feilong ') ";
HSTMT hstmt2;

retcode2 = SQLAllocStmt( hdbc2, &hstmt2);
retcode2 = SQLSetStmtOption( hstmt2, SQL_CONCURRENCY, SQL_CONCUR_READ_ONLY);
retcode2 = SQLSetStmtOption( hstmt2, SQL_CURSOR_TYPE, SQL_CURSOR_FORWARD_ONLY);
retcode2 = SQLPrepare(hstmt2, SQLstring, SQL_NTS);

if (retcode2 == SQL_SUCCESS || retcode2 == SQL_SUCCESS_WITH_INFO)
{
retcode2 = SQLExecute(hstmt2);
if(retcode2 == SQL_SUCCESS)
printf( "Succeeded!\n ");
else
printf( "Failed!\n ");
}


if (retcode2 != SQL_SUCCESS)
{
printf( "Failed!\n ");
SQLFreeStmt( hstmt2, SQL_DROP);
S