① 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控件的话,连接字串可以自己生成,在控件的属性里面找到拷贝就行,这种最简单