110,546
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace 显示表中数据2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection mysql = new SqlConnection();
mysql.ConnectionString = "Data Source=localhost;Initial Catalog=MyBookShop;Integrated Security=True";//数据库名
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = mysql;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = "SELECT * FROM Category";//表名
mysql.Open();
SqlDataReader sqlDateRreader;
sqlDateRreader = sqlCommand.ExecuteReader();
while (sqlDateRreader.Read())
{
richTextBox1.Text += " " + sqlDateRreader["CategoryID"].ToString() + "\t"
+ sqlDateRreader["CategoryName"].ToString() + "\r";//表里面有两列---CategoryID和CategoryName
}
Console.WriteLine(richTextBox1.Text);
mysql.Close();
sqlDateRreader.Close();
}
}
}
string connectionString;
public SqlDB()
{
connectionString = System.Configuration.ConfigurationSettings.AppSettings["connectionString"];
}
public bool ExecutInsert(string StrCommand)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connectionString;
conn.Open();
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = StrCommand;
if (comm.ExecuteNonQuery() > 0)
{
return true;
}
else
{
return false;
}
}
....
<appSettings>
<add key="connectionString" value="Data source=WLF-006\SQLEXPRESS;Database=RockTest;Trusted_Connection=True;" />
</appSettings>
System.Data.SqlClient.SqlConnection conn = new SqlConnection(connStr); //创建连接对象
System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand(); //创建命令对象
cmd.CommandText = "select Name from [User] where ID=1"; //定义查询语句
conn.Open(); //打开数据库
Console.WriteLine(cmd.ExecuteScalar());
conn.Close(); //关闭连接
conn.Dispose(); //释放资源