通用企业网站系统V3.0、Web项目开发,B2B/B2C电子商务系统开发,软件开发,网站建设,网页设计,UI设计。|
ADO.NET连接SQL Server2005数据库
ADO.NET连接SQL Server2005数据库
using System;
using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; namespace amin { class Program { static void Main(string[] args) { SqlConnection objSqlConnection = null; try { /** * server:服务器名称或者服务器ID,uid:访问数据库身份,pwd:访问数据库密码;database:应用程序将要操作的数据库名称 * * 本程序IP:localhost * 数据库身份:sa * 数据密码:0000 * 访问数据库:flying * * 数据库版本 SQL Server2005 * * * */ string url = "server=localhost;uid=sa;pwd=sa;database=Msdb";
//建立数据库连接 objSqlConnection = new SqlConnection(url); //开启链接 objSqlConnection.Open(); //SQL语句 string sql = "insert into flight(FNumber,FCompany,Fseat,EndStation,beginStation,beginTime,endTime) "+ "values('N020','beijing',4,'gz','gz','2009-01-01','2009-01-01')"; //SqlCommand指定要对数据库进行的操作,向数据库传递请求。 SqlCommand objSqlCommand = new SqlCommand(); //指定使用的数据库连接,SqlCommand使用此链接操作数据库。 objSqlCommand.Connection = objSqlConnection; //数据库请求 objSqlCommand.CommandText = sql; //指定SqlCommand对象的命令行SQL语句,如Update,Insert,Delelete,并返回SQL语句受影响的行数。 int i=objSqlCommand.ExecuteNonQuery(); if (i != 0) { Console.WriteLine("添加成功!"); } else { Console.WriteLine("添加失败!"); } //下面可以试验下更新和删除操作.................... }
catch (SqlException ex)//数据库连接异常 { Console.WriteLine(ex.Message); } catch (System.InvalidOperationException ex)//如果不开启数据库链接,将报此异常,ExecuteNonQuery方法活动连接没有打开。 { Console.WriteLine(ex.Message); } catch(Exception ex)//未知异常 { Console.WriteLine(ex.Message); } finally { if (objSqlConnection != null) { //关闭数据库连接 objSqlConnection.Close(); } }// finally结束.............. }//main方法结束.............. }//Programl类结束.................... } |
CopyRight