连接数据库的方法(自己使用)

C#(Asp.net)

 

using System.Data.SqlClient

    public string getstring()
    
{
        
//读取数据库连接字符串
        string settings = Convert.ToString(ConfigurationManager.ConnectionStrings["WebConnectionString"]);
        
return settings;
    }

然后在代码中调用.代码中使用到了存储过程CheckUser.

    //检查用户名地址是否可用,true表示用户名存在,false则表示不存在
    public bool IsUsed(string account)
    
{
        SqlConnection myconn 
= new SqlConnection(getstring());
        
//打开数据库连接
        myconn.Open();

        
//创建数据库命令
        SqlCommand mycmd = new SqlCommand("CheckUser", myconn);
        
//设置数据库命令类型为存储过程
        mycmd.CommandType = CommandType.StoredProcedure;

        
//命令参数
        SqlParameter accountparameter = mycmd.Parameters.Add("@UserAccount", SqlDbType.NVarChar, 50);
        accountparameter.Value 
= account;

        SqlDataReader mydr 
= mycmd.ExecuteReader();
        
try
        
{
            
if (mydr.Read())
            
{
                
return true//用户存在
            }

            
else
            
{
                
return false;//用户不存在
            }

        }

        
finally
        
{
            
//关闭操作
            mydr.Close();
            myconn.Close();
        }

    }

VB.net

        '运行即尝试链接数据库.如果失败则提示
        Dim conn As SqlConnection = New SqlConnection("Data Source=.;Initial Catalog=AccountRecord;Integrated Security=True")
        Try
            conn.Open()
            
'MessageBox.Show("链接数据库成功", "测试结果", MessageBoxButtons.OK, MessageBoxIcon.Information)
            conn.Close()
        Catch ex As Exception
            MessageBox.Show(
"链接数据库失败,请检查数据连接,错误消息如下:" + ex.ToString, "连接错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
原文地址:https://www.cnblogs.com/luoweihua7/p/1305518.html