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 testDataSet
{
public partial class Form1 : Form
{
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataAdapter sda = null;
DataSet ds = null;
public DataSet GetDS()
{
String sqlStr = "select name,sex,guanxi from tongxunru";
String connStr = @"Data Source = 127.0.0.1;Initial Catalog=mytest;User ID=sa;Password=Aa1234";
conn = new SqlConnection(connStr);
cmd = conn.CreateCommand();
cmd.CommandText = sqlStr;
sda = new SqlDataAdapter(cmd);
ds = new DataSet();
//conn.Open();
sda.Fill(ds);
// conn.Close();
return ds;
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 s1 = new Form1();
DataSet ds1 = s1.GetDS();
View1.DataSource = ds1.Tables[0];
}
1.请问为什么不需要conn.Open()就能顺利运行代码呢?
2.请问我上面写的调用DataSet方法合理吗?实际操作过程中大家也都是用类似的方法来做的吗?我的目的就是为了不需要太多的重复定义connection,command,adapter适配器等操作,繁锁也没必要。
新人,请多多指教。
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 testDataSet
{
public partial class Form1 : Form
{
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataAdapter sda = null;
DataSet ds = null;
public DataSet GetDS()
{
String sqlStr = "select name,sex,guanxi from tongxunru";
String connStr = @"Data Source = 127.0.0.1;Initial Catalog=mytest;User ID=sa;Password=Aa1234";
conn = new SqlConnection(connStr);
cmd = conn.CreateCommand();
cmd.CommandText = sqlStr;
sda = new SqlDataAdapter(cmd);
ds = new DataSet();
//conn.Open();
sda.Fill(ds);
// conn.Close();
return ds;
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 s1 = new Form1();
DataSet ds1 = s1.GetDS();
View1.DataSource = ds1.Tables[0];
}
1.请问为什么不需要conn.Open()就能顺利运行代码呢?
2.请问我上面写的调用DataSet方法合理吗?实际操作过程中大家也都是用类似的方法来做的吗?我的目的就是为了不需要太多的重复定义connection,command,adapter适配器等操作,繁锁也没必要。
新人,请多多指教。



