當前位置:首頁 » 數據倉庫 » c窗體鏈接資料庫
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

c窗體鏈接資料庫

發布時間: 2023-07-14 08:13:11

① c#窗體怎麼與資料庫連接

1.引入命名空間
using System.Data.sqlClient;
2.創建資料庫連接對象
SqlConnection對象名= new SqlConnection("server=.;database=NewQQ;uid=sa;pwd=123456");
3.打開資料庫連接
對象名.Open();

② 如何在C#窗體程序中連接資料庫並實現增、刪、改、查啊我不會連接資料庫,也不會在裡面寫代碼實現增刪改查

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;
using System.Collections.Generic;
namespace CeptAuto.DBUtility
{
/// <summary>
/// 數據訪問抽象基礎類
/// Copyright (C) 2004-2008 By LiTianPing
/// </summary>
public abstract class DbHelperSQL
{
//資料庫連接字元串(web.config來配置),可以動態更改connectionString支持多資料庫.
public static string connectionString = PubConstant.ConnectionString;
public DbHelperSQL()
{
}

#region 公用方法
/// <summary>
/// 判斷是否存在某表的某個欄位
/// </summary>
/// <param name="tableName">表名稱</param>
/// <param name="columnName">列名稱</param>
/// <returns>是否存在</returns>
public static bool ColumnExists(string tableName, string columnName)
{
string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
object res = GetSingle(sql);
if (res == null)
{
return false;
}
return Convert.ToInt32(res) > 0;
}
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
public static bool Exists(string strSql)
{
object obj = GetSingle(strSql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 表是否存在
/// </summary>
/// <param name="TableName"></param>
/// <returns></returns>
public static bool TabExists(string TableName)
{
string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
//string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
object obj = GetSingle(strsql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
public static bool Exists(string strSql, params SqlParameter[] cmdParms)
{
object obj = GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
#endregion

#region 執行簡單SQL語句

/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSql(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}

public static int ExecuteSqlByTime(string SQLString, int Times)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}

/// <summary>
/// 執行多條SQL語句,實現資料庫事務。
/// </summary>
/// <param name="SQLStringList">多條SQL語句</param>
public static int ExecuteSqlTran(List<String> SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
SqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
int count = 0;
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
count += cmd.ExecuteNonQuery();
}
}
tx.Commit();
return count;
}
catch
{
tx.Rollback();
return 0;
}
}
}
/// <summary>
/// 執行帶一個存儲過程參數的的SQL語句。
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <param name="content">參數內容,比如一個欄位是格式復雜的文章,有特殊符號,可以通過這個方式添加</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSql(string SQLString, string content)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(SQLString, connection);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 執行帶一個存儲過程參數的的SQL語句。
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <param name="content">參數內容,比如一個欄位是格式復雜的文章,有特殊符號,可以通過這個方式添加</param>
/// <returns>影響的記錄數</returns>
public static object ExecuteSqlGet(string SQLString, string content)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(SQLString, connection);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 向資料庫里插入圖像格式的欄位(和上面情況類似的另一種實例)
/// </summary>
/// <param name="strSQL">SQL語句</param>
/// <param name="fs">圖像位元組,資料庫的欄位類型為image的情況</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(strSQL, connection);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}

/// <summary>
/// 執行一條計算查詢結果語句,返回查詢結果(object)。
/// </summary>
/// <param name="SQLString">計算查詢結果語句</param>
/// <returns>查詢結果(object)</returns>
public static object GetSingle(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}

public static object GetSingle(string SQLString, int Times)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// 執行查詢語句,返回SqlDataReader ( 注意:調用該方法後,一定要對SqlDataReader進行Close )
/// </summary>
/// <param name="strSQL">查詢語句</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string strSQL)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(strSQL, connection);
try
{
connection.Open();
SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}

}
/// <summary>
/// 執行查詢語句,返回DataSet

③ C#寫的windows窗體應用程序,怎麼連接到資料庫並將數據插入到資料庫中

假設你用的是SQL數據,伺服器在名為server機器上,SQL伺服器用戶名Sa,密碼:123,表名為manager,表欄位為你圖上顯示的五個欄位(賬號,姓名,姓別,年齡,聯系方式),那麼你確定按扭單擊事件里可以這樣寫(要包含命銷叢禪名空間using System.Date;using System.Data.SqlClient)x0dx0a{ x0dx0aSqlConnection SqlConn = New SqlConnection(""Data Source=server;Initial Catalog=manager;Persist Security Info=True;User ID=sa;Password=123);x0dx0astring str="insert into manager(賬號,姓名,姓別,年齡,聯系方式) values('"+賬號textbox.text+"','"+姓名textbox.text+"','"+姓別textbox.text+"','"+年齡textbox.text+"','"+聯系方式textbox.text+"')";/*注意中間的單雙引號虧塵*/x0dx0aSqlCommand SqlCmd = New SqlCommand(str, SqlConn);x0dx0aSqlConn .Open();x0dx0aSqlCmd .ExecuteNonQuery();x0dx0aSqlConn .close();x0dx0a}x0dx0a正常的鄭舉話這樣就可以插入數據了.

④ c連接oracle資料庫的連接語句

連接代碼如下:
int main()
{
EXEC SQL BEGIN DECLARE SECTION;
char oc_passwd[101]; /*資料庫密碼*/
char oc_userid[101]; /*資料庫用戶名*/
char oc_dbname[101]; /*資料庫名*/
char oc_coad[101];
EXEC SQL END DECLARE SECTION;

memset(oc_passwd, 0x00, sizeof(oc_passwd));
memset(oc_userid, 0x00, sizeof(oc_userid));
memset(oc_dbname, 0x00, sizeof(oc_dbname));

/*取資料庫用戶名*/
strcpy(oc_userid, "userid");

/*取資料庫用戶密碼*/
strcpy(oc_passwd, "passwd") ;

/*取資料庫名*/
strcpy(oc_dbname, "dbname");

EXEC SQL CONNECT :oc_userid
IDENTIFIED BY :oc_passwd
USING :oc_dbname;
if (sqlca.sqlcode != 0)
{
printf("用戶名[%s]密碼[%s]資料庫[%s]\n", oc_userid, oc_passwd, oc_dbname);
printf("連接資料庫失敗,sqlcode=%d\n", sqlca.sqlcode);
return -1;
}
/*讀table取coad欄位*/
memset(oc_coad, 0x00, sizeof(oc_coad));
EXEC SQL SELECT coad
INTO :oc_coad
FROM table
WHERE 1=1;
if (sqlca.sqlcode == NORECORD)
{
printf("查詢無記錄\n");
return -1;
}
else if (sqlca.sqlcode != 0)
{
printf("查詢失敗,sqlcode=%d\n", sqlca.sqlcode);
return -1;
}
return 0;
}

c語言如何與ACCESS或MYSQL資料庫連接

C語言連接 Access 數據納鬧亂庫
首先在網路搜索 odbc 連接字元串 找到的是asp連接Access的方法,但是ODBC是通用的,所以直接拿過來也能用。

SQLCHAR ConnStrIn[MAXBUFLEN] = 「DRIVER={MySQL ODBC 5.1 Driver};SERVER=127.0.0.1;UID=root;PWD=root;DATABASE=test;CharSet=gbk;「;
部分改成
SQLCHAR ConnStrIn[MAXBUFLEN] = 「Driver={Microsoft Access Driver (*.mdb)};Dbq=//mydatabase.mdb;Uid=Admin;Pwd=;CharSet=gbk;「;
Dbq指的是你的資料庫所在路勁
當然之前你應該在c:/下新建一個資料庫名為mydatabase.mdb,而且如果後面的SQL操作語句是老師寫的
result = SQLPrepare(hstmt,(SQLCHAR*)「* into T_Person(FAge,FName) values(20,'kider'洞檔)「,SQL_NTS);
那麼你也要在之前建立好一個表T_Person,和表中的兩個欄位FAge,FName.否則會出錯。
怎麼樣,已經成功鏈接彎凳到Access了吧,接下來你就可以發揚廣大了,做個管理系統之類的東東

⑥ 用C語言怎麼實現與資料庫的連接

#include<mysql/mysql.h>

#include<stdio.h>

intmain()

{

MYSQL*conn;

MYSQL_RES*res;

MYSQL_ROWrow;

char*server="localhost";//本地連接

char*user="root";//

char*password="525215980";//mysql密碼

char*database="student";//資料庫名

char*query="select*fromclass";//需要查詢的語句

intt,r;

conn=mysql_init(NULL);

if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0))

{

printf("Errorconnectingtodatabase:%s ",mysql_error(conn));

}else{

printf("Connected... ");

}

t=mysql_query(conn,query);

if(t)

{

printf("Errormakingquery:%s ",mysql_error(conn));

}else{

printf("Querymade... ");

res=mysql_use_result(conn);

if(res)

{

while((row=mysql_fetch_row(res))!=NULL)

{

//printf("num=%d ",mysql_num_fields(res));//列數

for(t=0;t<mysql_num_fields(res);t++)

printf("%8s",row[t]);

printf(" ");

}

}

mysql_free_result(res);

}

mysql_close(conn);

return0;

}

(6)c窗體鏈接資料庫擴展閱讀

C語言使用注意事項:

1、指針是c語言的靈魂,一定要靈活的使用它:

(1)、指針的聲明,創建,賦值,銷毀等

(2)、指針的類型轉換,傳參,回調等

2、遞歸調用也會經常用到:

(1)、遞歸遍歷樹結構

(2)、遞歸搜索

⑦ c或c++連接資料庫,求代碼,求指教,很急!

對於SQL Server資料庫,
C++使用猛大MFC庫,主要有兩種方法租知顫可以連接sql資料庫
1.利用ADO連接:
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
//必須import這個dll,這個文件通常放在C:\Program Files\Common Files\System\ado路徑下.
_ConnectionPtr m_ptrConnection; //資料庫連接對象
構造函數中添加如下語句
m_ptrConnection = NULL;
::CoInitialize(NULL);
//連接資料庫的主要代碼
BOOL DataVisitor::ConnectDataBase(_bstr_t connectionStr)
{
/*
Added by stone. If IDOConnection has not been set up,then create one.
*/
if(m_ptrConnection == NULL)
{
HRESULT hr = m_ptrConnection.CreateInstance(__uuidof(Connection));
if (FAILED(hr))
{
return FALSE;
}
else
{
_bstr_t strConnect = connectionStr;
//"Provider=SQLOLEDB;Server=(local);Database=navigation; uid=sa; pwd=3277625;";

m_ptrConnection->CursorLocation = adUseClient;
m_ptrConnection->IsolationLevel = adXactReadCommitted;
try
{
m_ptrConnection->Open(strConnect,"","",adModeUnknown);
return TRUE;
}
catch (_com_error e)
{
// AfxMessageBox((char *)e.Description());
return FALSE;
}

}
}
return TRUE;
}

2. 利用ODBC連接
#include <afx.h>
CDaoDatabase *MyDataBase;

BOOL MyDB_OperSqL::Open_MyDatabase(CString connstr)
{
try
{
if (MyDataBase == NULL)
{
MyDataBase = new CDaoDatabase();
}
MyDataBase->Open(NULL,0,0,connstr);

}
catch( CDaoException* e )
{
CString message = _T("MyDB_OperSqL 資料庫異常: ");
message += e->m_pErrorInfo->m_strDescription;
char info[400];
sprintf(info,message);
DispErrorMessage(info,__LINE__);
e->弊敗Delete( );
return FALSE;
}
catch (CMemoryException *e)
{
DispErrorMessage("MyDB_OperSqL 內存異常!",__LINE__);
e->Delete( );
return FALSE;
}
catch(...)
{
DispErrorMessage("MyDB_OperSqL 其它異常!",__LINE__);
return FALSE;
}
return TRUE;
}
這里的連接字元串connstr一般是如下內容
"ODBC;DRIVER={SQL Server};SERVER=(local);DATABASE=yourDataBase;UID=yourID;PWD=yourPassword"

如果直接用Microsoft ADO Datebase Control控制項的話,連接字串可以自己生成,在控制項的屬性裡面找到拷貝就行,這種最簡單