2014-05-15 3 views
0

textbox 입력에서 데이터베이스 테이블을 검색하는 데이터베이스에서 쿼리를 실행하려고합니다. 나는 밖으로 나가 오류가 connection.Open()에서 발생 볼 수있는 캐치을 촬영하면 내 코드데이터베이스에 연결 중 - connectString connect.Open() 오류

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Data.SqlClient; 

namespace Query 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void employeeBindingNavigatorSaveItem_Click(object sender, EventArgs e) 
     { 
      this.Validate(); 
      this.employeeBindingSource.EndEdit(); 
      this.tableAdapterManager.UpdateAll(this.personnelDataSet); 

     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      // TODO: This line of code loads data into the 'personnelDataSet.employee' table. You can move, or remove it, as needed. 
      this.employeeTableAdapter.Fill(this.personnelDataSet.employee); 

     } 

     private void btnExit_Click(object sender, EventArgs e) 
     { 
      this.Close(); 
     } 

     string connectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"; 

     private void btnSearch_Click(object sender, EventArgs e) 
     { 
      string commandText = "SELECT employeeID, name, position, hourlyPayRate " + 
        "FROM dbo.employee WHERE name LIKE '%'+ @Name + '%'"; 

      using (SqlConnection connection = new SqlConnection(connectionString)) 
      { 
       //Create a SqlCommand instance 
       SqlCommand command = new SqlCommand(commandText, connection); 
       //Add the parameter 
       command.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = textBox1.Text; 

       //Execute the query 
       try 
       { 
        connection.Open(); 
        command.ExecuteNonQuery(); 
       } 
       catch 
       { 
        //Handle excepetion, show message to user... 
        MessageBox.Show("Error bitch!"); 
       } 
       finally 
       { 
        connection.Close(); 
       } 
      } 
     } 
    } 
} 

입니다. 이 오류는 나를 string connectionString = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";

이에 문제가 있는지 궁금해하는하게 일어나는 동안이다 걸리는 I 나타나는 오류 :

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll 
+0

의 아마 당신의 연결 문자열을

또 다른 방법은 다음과 같이 Web.config를 통해 데이터베이스를 연결하는 것입니다. 당신은 ssms있어? 연결 문자열을 확인할 수 있습니까? –

+0

나는 ssms가 없다. 어떻게 확인할 수 있습니까? – Matt

+0

연결 고리입니다. 복사 - 붙여 넣기를 통해 일반 연결을 방금 가져 왔습니다. 실제로 serveraddress 등을 채우십시오. – Matthijs

답변

0

확인이 아웃 : 또한

string connectionString = "Server=.\InstanceName;Database=myDataBase;Integrated Security=True;"; 

string commandText = "SELECT employeeID, name, position, hourlyPayRate 
        FROM dbo.employee WHERE name LIKE '%@Name%'"; 
0

try :

string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User id=myUser;Password=myPAss;Connect Timeout=15;Integrated Security=false"; 
+0

이것은 연결 문자열 문제를 해결하는 데 도움이되지 않을 것입니다. – MoonKnight

1

연결 문자열의 유효성을 검사해야합니다. Open()SqlException을 던지면 연결 문자열이 유효하지 않습니다. 필요한 연결 문자열의 정확한 형식을 설정하려면 connectionstrings.com을 살펴보십시오.

try 
{ 
    connection.Open(); 
    command.ExecuteNonQuery(); 
} 
catch (Exception e) 
{ 
    // Handle excepetion, show message to user... 
    MessageBox.Show(e.Message); 
} 

난이 도움이되기를 바랍니다 : 예외로 unhanded 보여주는 이유에

, 당신은 다음과 같이 예외를 '소비'할 필요가있다.

+0

감사합니다. 제발 예외가 있습니다. 그냥 연결 문자열의 유효성을 검사하는 방법에 대해 알지 못합니다. – Matt

+0

안녕 Matt, 무엇을 연결하려고합니까? connectionstrings.com에 대한 링크 편집을 참조하십시오. 귀하의 상황에 맞는 연결 문자열의 형태. – MoonKnight

0

이벤트 내에서 연결 문자열을 선언 해보십시오.

<connectionStrings> 
    <connectionString="Data Source=(localdb)\v11.0;Initial Catalog=DBName;Integrated Security=True" providerName="System.Data.SqlClient"/> 
    </connectionStrings> 

를 그리고 연결 문자열로 할 수있다 : 고장

string cs = ConfigurationManager.ConnectionStrings["DBName"].ConnectionString; 
관련 문제