日期:2014-05-18 浏览次数:21420 次
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.Data.SqlClient; namespace WindowsApplication3 { public partial class Form1 : Form { bool Return=true; AutoResetEvent sleepSynchro = new AutoResetEvent(false); Exception err = null; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Thread controlThread = new Thread(new ThreadStart(test)); controlThread.Start(); if (!sleepSynchro.WaitOne(3000, false)) { MessageBox.Show("数据库连接超时.", "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (!Return) { MessageBox.Show("数据库连接失败:" + err.Message, "错误:", MessageBoxButtons.OK, MessageBoxIcon.Error); } } void test() { string sqlconn = @"Data Source=3.0.0.0;Initial Catalog=eDocument;Integrated Security=True"; SqlConnection conn = new SqlConnection(sqlconn); try { conn.Open(); Return = true; } catch (Exception e) { Return = false; err = e; } finally { conn.Close(); sleepSynchro.Set(); } } } }
------解决方案--------------------
string str="server={0};database={1};uid={2};pwd={3};Connection Timeout={4} "; str=String.Format(str,Server,DBName,UserId,Passwd,5); SqlConnection Conn=new qlConnection(str); Conn.Open(); //5秒这个时间是指数据库连接的时间,不包括解析IP地址、寻找机器的时间,而且第一次连接会慢很多, //所以LZ可以把时间设置打点
------解决方案--------------------
让程序判断 try...catch 是最好
------解决方案--------------------
public DataTable getDataTable(string strSQL)
{
DataTable dt1 = new DataTable();
using (SqlConnection myConnection = new SqlConnection(connetion))
{
SqlDataAdapter da = new SqlDataAdapter(strSQL, myConnection);
da.SelectCommand.CommandTimeout = 1000;
da.SelectCommand.CommandType = CommandType.Text;
da.Fill(dt1);
da.Dispose();
myConnection.Close();
myConnection.Dispose();
}
return dt1;
}