操作数据库

来源:互联网 发布:解决网络高峰期问题 编辑:程序博客网 时间:2024/05/29 19:10
一、创建索引
create index 索引名
on 表名(字段)


二、创建存储过程(3种)
1、--创建简单的存储过程
create proc proUserInfo
as
select * from T_UserInfo;
go
--调用存储过程
exec proUserInfo
2、--创建带输入参数的存储过程
create proc proUserInfo1
@name varchar(20)
as
select * from T_UserInfo WHERE Name=@name
go
--调用存储过程
exec proUserInfo1 '姓名'
3、--创建带2个输入参数的存储过程
create proc proUserInfo2
@name varchar(20),
@age int
as
select * from T_UserInfo where Name=@name or Age=@age
go
--调用存储过程
exec proUserInfo2 '姓名',18
4、--带输出参数的存储过程
create proc proUserInfo3
@name varchar(20),
@age int output
as
select @age=age from T_UserInfo WHERE Name=@name
GO
--调用存储过程
begin
declare @age int
exec proUserInfo3 '随便',@age output
select @age
end


三、将记事本中的数据导入数据库
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void btnXuanZe_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = this.openFileDialog1.FileName;
            }  
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            string strcon = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;
            SqlConnection sqlcnn = new SqlConnection(strcon);
            SqlCommand sqlcmm = sqlcnn.CreateCommand();
            //sqlcmm.Connection = sqlcnn;
            sqlcmm.CommandText = "bulk insert T_txt from '" + textBox1.Text + "' with (fieldterminator='|',rowterminator='\n')";
            sqlcnn.Open();
            int i = sqlcmm.ExecuteNonQuery();
            if (i > 0)
            {
                MessageBox.Show("添加成功!");
            }
            else
            {
                MessageBox.Show("添加失败!");
            }       
        }
}


四、数据从一数据库到另一数据库
namespace 数据从一数据库到另一数据库
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void btnChange_Click(object sender, EventArgs e)
        {
           
            string str = "server=.;initial catalog=MyFirst;integrated security=true";
            using (SqlConnection con = new SqlConnection(str))
            {
                using (SqlCommand com = con.CreateCommand())
                {
                    com.CommandText = "select * into FIRST.dbo.T_UserInfo from MyFirst.dbo.T_UserInfo";
                    con.Open();
                    int i=Convert.ToInt32(com.ExecuteNonQuery());
                    if (i > 0)
                    {
                        MessageBox.Show("导入成功");
                    }
                    else
                    {
                        MessageBox.Show("导入失败");
                    }
                }
            }
        }
    }
}