ppt封面图片淡雅:C#连接数据库(sql2000)并使用数据库

来源:百度文库 编辑:中财网 时间:2024/05/10 07:15:24

C#怎么连接数据库并使用数据库啊?
 悬赏分:50 - 解决时间:2009-6-8 08:54
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace database
{
    public partial class Form1 : Form
    {
        //定义什么变量?
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //这里是连接数据库并使用数据库的代码怎么写啊?
          
        }
    }
}

提问者: 355884441 - 四级最佳答案以下是一个C#与数据库操作的通用类完整代码,几乎可以进行所有的操作。不要在代码中出现SQL语句,要用存储过程,这样才能保证数据的安全。
 public class DBHelper
    {
        private static SqlConnection connection;
        private static SqlCommand command;
        private static SqlDataAdapter da;
        private static DataSet ds;
        private static string connString = "Data Source=服务器名;Initial Catalog=数据库名;Integrated Security=true";//用windows身份登录

        //连接属性:用于实例化连接对象并打开连接对象
        public static SqlConnection Connection
        {
            get
            {
                if (connection == null)
                {
                    connection = new SqlConnection(connString);
                }
                if (connection.State==ConnectionState.Broken || connection.State==ConnectionState.Closed)
                {
                    connection.Open();
                }
                return connection;
            }           
        }

        ///


        /// 通过SQL语句从数据库返回单个值
        ///

        /// SQL语句
        /// 返回值:1、0、-1
        public static int GetScalar(string strSql)
        {
            try
            {
                command = new SqlCommand(strSql,connection);
                connection.Open();
                int i = (int)command.ExecuteScalar();
                return i;
            }
            catch (Exception)
            {
                connection.Close();
                return -1;
            }
        }

        ///


        /// 通过存储过程及参数返回单个值
        ///

        /// 存储过程名
        /// 参数集合
        /// 返回单个值
        public static object GetScalar(string storedProcedureName, params SqlParameter[] parameters)
        {
            try
            {
                //将存储过程封装在命令对象
                command = new SqlCommand(storedProcedureName, Connection);
                //指定命令对象执行的类型为存储过程
                command.CommandType = CommandType.StoredProcedure;
                //将参数添加到命令对象的参数集合中
                command.Parameters.AddRange(parameters);
                //执行命令
                object o = command.ExecuteScalar();
                //关闭连接
                connection.Close();
                //返回对象
                return o;
            }
            catch (Exception)
            {
                connection.Close();
                return null;
            }
        }

        ///


        /// 通过存储过程及参数查询返回数据集
        ///

        /// 存储过程名
        /// 参数集合
        /// 返回数据集
            public static DataSet GetDataSet(string storedProcedureName, params SqlParameter[] parameters)
            {
                //将存储过程封装在命令对象
                command = new SqlCommand(storedProcedureName, Connection);
                //指定命令执行的类型为存储过程
                command.CommandType = CommandType.StoredProcedure;
                //将参数添加到命令对象的参数集合中
                command.Parameters.AddRange(parameters);

                da = new SqlDataAdapter(command);
                ds = new DataSet();
                da.Fill(ds);
            return ds;
        }

        ///


        /// 通过存储过程及参数执行对表的增删改操作
        ///

        /// 存储过程名
        /// 参数集合
        /// 返回操作是否成功
        public static bool Execute(string storedProcedureName,params SqlParameter[] parameters)
        {
            try
            {
                command = new SqlCommand(storedProcedureName, Connection);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddRange(parameters);

                command.ExecuteNonQuery();
                connection.Close();
                return true;
            }
            catch (Exception)
            {
                connection.Close();
                return false;
            }           
        }
    }

 7回答者: 418228329 - 三级   2009-6-2 01:57


其他回答    共 3 条
string connstr = "Data Source=(local); database=数据库名; user id=登录名; password=密码";

        string sql = "select * from char_test";//sql语句
        SqlConnection conn = new SqlConnection(connstr);
        conn.Open();
        try
        {
           
            SqlCommand comm = new SqlCommand(sql, conn);
            SqlDataReader reader = comm.ExecuteReader();

            if (reader.Read())
                TextBox2.Text = reader[0].ToString();


        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
         finally
        {
            conn.Close();
        }

回答者: dggen - 六级   2009-6-1 22:20

string sql = "select * from char_test";//sql语句
        SqlConnection conn = new SqlConnection(connstr);
using(conn){
 conn.Open();
 try
        {
           
            SqlCommand comm = new SqlCommand(sql, conn);
            SqlDataReader reader = comm.ExecuteReader();

            if (reader.Read())
                TextBox2.Text = reader[0].ToString();


        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
      
}

 

一:C# 连接SQL数据库

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;
Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=True;
Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;

1:Integrated Security参数
    当设置Integrated Security为 True 的时候,连接语句前面的 UserID, PW 是不起作用的,即采用windows身份验证模式。
    只有设置为 False 或省略该项的时候,才按照 UserID, PW 来连接。
    Integrated Security 还可以设置为:sspi ,相当于 True,建议用这个代替 True。
    Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
    Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=true;
    Data Source=myServerAddress;Initial Catalog=myDataBase;;User ID=myUsername;Password=myPasswordIntegrated Security=false;

2:参数Trusted_Connection
    Trusted_Connection=true,将使用当前的   Windows   帐户凭据进行身份验证
    Trusted_Connection=false;将不采用信任连接方式(也即不采用Windows验证方式),而改由SQL Server 2000验证方式
    Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=false;
    Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

3:Initial Catalog是你要连接的数据库的名字

4:WINCE连接
    Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomain\myUsername;Password=myPassword;

二:可以利用SqlConnectionStringBuilder,这样不必去记住名称。
    SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder();
    scsb.DataSource = @"(local)\SQLExpress";
    scsb.IntegratedSecurity = true;
    scsb.InitialCatalog = "Northwind";
    SqlConnection myConnection = new SqlConnection(scsb.ConnectionString);

三:可以利用属性中的Setting来自动设置连接字符串
    1:在type中选择 (connection string),
    2:在DataSouce中选择数据源,然后再Server中输入服务器名,本地用(local)\SQLExpress
    3:选择登陆验证方式,本次选Windows验证(即信任连接Integrated Security=True)
    4:选择数据库名,确认即可
    Data Source=(local)\SQLExpress;Initial Catalog=Northwind;Integrated Security=True
    server = .\sqlexpress;integrated security = true;database = northwind

四:SQL2005远程服务器连接方法

如何打开sql server 2005 的1433端口:
配置工具->Sql Server Configuration Manager->MSSQLSERVER的协议看看TCP/IP协议是否启动,如果启动,右键菜单点"属性" ,在分页菜单中选"IP地址",把"IP1"和"IP2"中"TCP端口"为1433,"已启用"改为"是"
配置工具->Sql Server Configuration Manager->SQL Native Client 配置->客户端协议->TCP/IP选择TCP/IP右键菜单中"属性",确认"默认端口"是1433,"已启用"为"是"。

SQL Server 2005 远程连接配置TCP/IP属性:
Surface Area Configuration --> Database Engine --> Remote Connections --->Using TCP/IT SQL Server 外围应用配置器?服务和连接外围配置?database englie?远程连接?启用(远程连接的TCP/IP和named pipes)
SQL Server Configuration Manager?SQL2005网络配置?启用TCP/IP和named pipes

其他说明见下: sqlserver2005(Express版),为了便于管理,你还需要去下一个manage管理器:
安装好manage管理器后,在程序中连接sqlserver2005,下面几点是要注意的。
1. 开启sql2005远程连接功能,开启办法如下, 配置工具->sql server外围应用配置器->服务和连接的外围应用配置器->打开MSSQLSERVER节点下的Database Engine 节点,先择"远程连接",接下建议选择"同时使用TCP/IP和named pipes",确定后,重启数据库服务就可以了.
2.登陆设置改为,Sql server and windows Authentication方式同时选中,具体设置如下: manage管理器->windows Authentication(第一次用windows方式进去),->对象资源管理器中选择你的数据服务器--右键>属性>security>Sql server and windows Authentication方式同时选中.
3:设置一个Sql server方式的用户名和密码,具体设置如下: manage管理器->windows Authentication>new query>sp_password null,'sa123456','sa' 这样就设置了一个用户名为sa ,密码为:sa123456的用户,下次在登陆时,可以用Sql server方式, 用户名为sa ,密码为:sa123456的用户进数据库了.
4: 做完上面三步后,这样写连接字符串就可以顺利进入数据库了,
(server=.\sqlexpress;uid=sa;pwd=sa123456;database=master";

五:SQL2000远程服务器连接方法

1:看ping 服务器IP能否ping通。
2:在Dos或命令行下输入telnet 服务器IP 端口,看能否连通。   如telnet 202.114.100.100 1433   通常端口值是1433,因为1433是sql server 2000的对于Tcp/IP的默认侦听端口。如果有问题,通常这一步会出问题。通常的提示是“……无法打开连接,连接失败"。   
    如果这一步有问题,应该检查以下选项。   
    1) 检查远程服务器是否启动了sql server 2000服务。如果没有,则启动。   
    2) 检查服务器端有没启用Tcp/IP协议,因为远程连接(通过因特网)需要靠这个协议。检查方法是,在服务器上打开 开始菜单-> 程序-> Microsoft SQL Server-> 服务器网络实用工具,看启用的协议里是否有tcp/ip协议,如果没有,则启用它。   
    3)检查服务器的tcp/ip端口是否配置为1433端口。仍然在服务器网络实用工具里查看启用协议里面的tcp/ip的属性,确保默认端口为1433,并且隐藏服务器复选框没有勾上。   事实上,如果默认端口被修改,也是可以的,但是在客户端做 telnet测试时,写服务器端口号时必须与服务器配置的端口号保持一致。如果隐藏服务器复选框被勾选,则意味着客户端无法通过枚举服务器来看到这台服务器,起到了保护的作用,但不影响连接,但是Tcp/ip协议的默认端口将被隐式修改为2433,在客户端连接时必须作相应的改变。   
    4)如果服务器端操作系统打过sp2补丁,则要对windows防火墙作一定的配置,要对它开放1433端口,通常在测试时可以直接关掉windows防火墙(其他的防火墙也关掉最好)。   
    5)检查服务器是否在1433端口侦听。如果服务器没有在tcp连接的1433端口侦听,则是连接不上的。检查方法是在服务器的dos或命令行下面输入  netstat -a -n 或者是netstat -an,在结果列表里看是否有类似 tcp 127.0.0.1 1433 listening 的项。如果没有,则通常需要给sql server 2000打上至少sp3的补丁。其实在服务器端启动查询分析器,输入 select @@version 执行后可以看到版本号,版本号在8.0.2039以下的都需要打补丁。  如果以上都没问题,这时你再做telnet 服务器ip 1433 测试,将会看到屏幕一闪之后光标在左上角不停闪动。恭喜你,你马上可以开始在企业管理器或查询分析器连接了。   

3: 检查客户端设置  程序-> Microsoft SQL Server -> 客户端网络使用工具。像在服务器网络实用工具里一样,确保客户端tcp/ip协议启用,并且默认端口为1433(或其他端口,与服务器端保持一致就行)。  
4:在企业管理器里或查询那分析器连接测试   企业管理器-> 右键SQlserver组-> 新建sqlserver注册-> 下一步-> 写入远程IP-> 下一步-> 选Sqlserver登陆-> 下一步-> 写入登陆名与密码(sa,password)-> 下一步-> 下一步-> 完成   查询分析器-> 文件-> 连接-> 写入远程IP-> 写入登录名和密码(sa,password)-> 确定  通常建议在查询分析器里做,因为默认情况下,通过企业管理器注册另外一台SQL Server的超时设置是4秒,而查询分析器是15秒。  修改默认连接超时的方法:   企业管理器-> 工具-> 选项-> 在弹出的"SQL Server企业管理器属性"窗口中,点击"高级"选项卡-> 连接设置-> 在 登录超时(秒) 后面的框里输入一个较大的数字  查询分析器-> 工具-> 选项-> 连接-> 在 登录超时(秒) 后面的框里输入一个较大的数字  通常就可以连通了,如果提示错误,则进入下一步。   
5:错误产生的原因通常是由于SQL Server使用了"仅 Windows"的身份验证方式,因此用户无法使用SQL Server的登录帐户(如 sa )进行连接。解决方法如下所示:   
    1) 在服务器端使用企业管理器,并且选择"使用 Windows 身份验证"连接上 SQL Server。   
    2) 展开"SQL Server组",鼠标右键点击SQL Server服务器的名称,选择"属性",再选择"安全性" 选项卡。   
    3)在"身份验证"下,选择"SQL Server和 Windows "。   
    4) 重新启动SQL Server服务。(在dos或命令行下面net stop mssqlserver停止服务,net start mssqlserver启动服务,也是一种快捷的方法)。
文章出处:DIY部落(http://www.diybl.com/course/4_webprogram/asp.net/netjs/20091106/181460.html)