c# - 我在哪里/如何在我的 C# 代码中编写 T-SQL 并获得结果 (Visual Studio 2008)

标签 c# visual-studio tsql

我正在尝试用 C# (visual studio) 编写 t-sql。我有这段代码连接到数据库:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using Microsoft.SqlServer.Server;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection cnn;
            connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Xtreme\\Desktop\\CardsDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
            cnn = new SqlConnection(connetionString);
            try
            {


                cnn.Open();
                MessageBox.Show("Connection Open ! ");

                cnn.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show("Can not open connection ! ");
            }


        }
    }
}

在哪里/如何编写 T-SQL 代码以及如何获得结果?

有人可以在我的代码中给我一个简单的选择示例吗?

最佳答案

您可以使用 DataAdapter.Fill方法:

try
{
    using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM Employee", cnn))
    {
        // Use DataAdapter to fill DataTable
        DataTable t = new DataTable();
        a.Fill(t);

        // Render data onto the screen
        dataGridView1.DataSource = t; //if you want.
    }
}
catch (Exception ex)
{
    MessageBox.Show("Problem!");
}

关于c# - 我在哪里/如何在我的 C# 代码中编写 T-SQL 并获得结果 (Visual Studio 2008),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4095554/

相关文章:

iphone - 需要替换 iPhone 项目中使用的 C 代码中 strcpy_s 的使用

sql - 如何删除关联SQL表中的行?

c# - iOS 应用程序启动错误

c# - 求和多维数组C#

c++ - 为什么这个专门用于 basic_ifstream 模板的 char_traits<uint8_t> 和 codecvt<uint8_t> 会抛出 std::bad_cast?

c# - Listview Itemediting 不工作

c# - Id POST 作为隐藏字段但在 Controller 中为空

c# - 编写跨平台位级代码时,字长和字节顺序会相互作用吗?

带有 "dynamic"where 子句的 SQL 语句

sql - 仅在 SQL Server 2005 中存储日期