连接到我的数据库 [英] Connection to my database

查看:67
本文介绍了连接到我的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我似乎无法连接到我的数据库 - 这是我的app.config:

 <? xml version =   1.0 encoding =    utf-8 ?>  
< 配置 >
< startup >
< supportedRuntime 版本 = v4.0 sku = 。NETFramework,Version = v4.5.2 / >

< connectionstrings >
< add name = 系列 connectionString = 数据源= .;初始目录=系列; IntegratedSecurity = True providerName = System.Data .SqlClient / >



和this是我的DB类中的代码:

  public   static  SqlConnection ConnectToDB(SqlConnection连接)
{
尝试
{
if (connection == null
connection = new SqlConnection (ConfigurationManager.ConnectionStrings [ Series]。ConnectionString);
connection.Open();

}
catch (例外情况)
{
抛出 ex;

}
connection = DB.DisconnectFromDB(connection);
返回连接;
}



- 数据库的名称我系列



什么我试过了:



我想我试过了,不能真正看到问题

解决方案

< blockquote>正如@NotPoliticallyCorrect所述 - 您需要使用调试器逐步执行代码,检查变量和程序流程,您可能能够理解正在发生的事情。本文应该可以帮助您掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]



你对Try-Catch的使用并不是真的合理 - 在升级它之前你没有添加任何东西,所以只需让它渗透通过线程。本文可能会帮助您 .NET中的异常处理最佳实践 [< a href =https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NETtarget =_ blanktitle =New Window> ^ ]



您的问题是

 connection = DB.DisconnectFromDB(connection); 

我不知道 DB 但是我猜这个 DisconnectFromDB 做了它说的话并断开了你精心设计的连接!



最后一点 - 我不会那样传递连接。在您的类中封装连接变量。对于一个简单的例子......

 使用 System.Configuration; 
使用 System.Data;
使用 System.Data.SqlClient;

命名空间沙盒
{
public class DbClass
{
private SqlConnection连接;

public bool ConnectToDb()
{
if (connection == null
connection = new SqlConnection(ConfigurationManager.ConnectionStrings [ ConnectToDB]。ConnectionString);

if (connection.State!= ConnectionState.Open)
connection.Open();

return (connection.State == ConnectionState.Open);
}
}
}

我可以这样打电话:

  var  xdb =  new  DbClass(); 
var b = xdb.ConnectToDb();
Debug.Print(b.ToString());

- 意味着调用模块不需要知道任何关于 System.Data.SqlClient ...这让生活变得更轻松如果我要切换数据库提供程序


从您的连接字符串开始:数据源。可能是开始的地方。

尝试使用Server Explorer窗格在VS中设置连接:

1)打开服务器资源管理器。

2)右键单击数据连接并选择添加连接

3)在随后的对话框中,选择您的DataSource和数据库,指定安全信息,然后按测试连接按钮。

4)连接工作时,按确定

5)在服务器资源管理器窗格中突出显示数据库,然后查看属性窗格。将显示连接字符串的工作示例,您可以将其复制并粘贴到app.config文件中。



您需要将其更改为生产,当然。


So i cant seem to connect to my database - This is my app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    
  <connectionstrings>
    <add name="Series" connectionString="Data Source=.;Initial Catalog=Series;IntegratedSecurity=True" providerName="System.Data.SqlClient" />


and this is my code in my DB class:

public static SqlConnection ConnectToDB(SqlConnection connection)
        {
            try
            {
                if (connection == null)
                    connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Series"].ConnectionString);
                connection.Open();
               
            }
            catch (Exception ex)
            {
                throw ex;
                
            }
            connection = DB.DisconnectFromDB(connection);
            return connection;
        }


- The name of the database i "Series"

What I have tried:

I think i tried everyting, cant really see the problem

解决方案

As @NotPoliticallyCorrect has stated - you need to step through your code with the debugger, examine variables and program flow and you might be able to understand what is going on. This article should help you Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

Your use of Try-Catch is not really sensible - you are not adding anything to the exception before escalating it, so just let it percolate up through the thread. This article might help you Exception Handling Best Practices in .NET[^]

Your problem is the line

connection = DB.DisconnectFromDB(connection);

I have no idea what DB is but I'm guessing that DisconnectFromDB does what it says and disconnects your carefully created connection!

On a final note - I wouldn't pass the connection around like that. Encapsulate the connection variable in your class. For a simplistic example...

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace Sandbox
{
    public class DbClass
    {
        private SqlConnection connection;

        public bool ConnectToDb()
        {
            if (connection == null)
                connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectToDB"].ConnectionString);

            if (connection.State != ConnectionState.Open)
                connection.Open();

            return (connection.State == ConnectionState.Open);
        }
    }
}

Which I can call like this:

var xdb = new DbClass();
  var b = xdb.ConnectToDb();
  Debug.Print(b.ToString());

- meaning the calling module does not need to know anything about System.Data.SqlClient ... which makes life a lot easier if I was to switch database provider


Start with your connection string: a Data Source of "." is probably the place to start.
Try setting up a connection in VS with the Server Explorer pane:
1) Open Server Explorer.
2) Right click "Data connections" and select "Add connection"
3) In the dialog that follows, select your DataSource, and database, specify the security info, and press the "Test connection" button.
4) When the connection works, press "OK"
5) Highlight your database in the Server Explorer pane, and look at the Properties pane. A working example of the connection string will be shown, which you can copy and paste into your app.config file.

You'll need to change it for production, of course.


这篇关于连接到我的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆