Read data tables of different databases in SqlServe

We operate in the SqlServer graphical interface under the premise of currently operating the database. The screenshots are as follows:
write picture description here
The tables in different databases are different in most cases. When we write Sql statements in c#, we must bring them with us. use.
If you check the table in the Test database, the Sql statement is as follows:

string sql="use Text;select * from sysobjects where xtype='U'";
  • 1

If you check the table in the Demo database, the Sql statement is as follows:

string sql="use Demo;select * from sysobjects where xtype='U'";
  • 1

The role of use is to switch the current operating database, and only use use to find all the table names in the expected database.
SqlServer parameterized query and stored procedure

In order to prevent Sql injection, we use the method of parameterized query, in order to save the compilation time of Sql statement, we use stored procedure. These two seemingly unrelated things are actually the same thing. If you don't believe me, let me explain to you.
Ordinary Sql statements can be added, deleted, modified and searched, and parameterized queries and stored procedures can also be added, deleted, modified and searched. Here, we will not write examples of the four operations one by one, but write examples of insert and select to illustrate the situation.

Parameterized query:

Execute parameterized query code:

public static int ParamInsert(string userId, string userName, string gender)
{
    int rowNumber = -100;
    string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();
    SqlConnection con = new SqlConnection(connString);
    con.Open();

    #region 参数化插入
    SqlCommand cmd1 = new SqlCommand("insert into UserInfo values(@userId,@userName,getdate(),@gender)", con);
    cmd1.Parameters.Add("@userId", SqlDbType.Int).Value = userId;
    cmd1.Parameters.Add("@userName", SqlDbType.NVarChar, 20).Value = userName;
    cmd1.Parameters.Add("@gender", SqlDbType.NVarChar, 2).Value = gender;
    rowNumber = cmd1.ExecuteNonQuery();
    cmd1.Dispose();
    #endregion

    #region 参数化查询
    SqlCommand cmd = new SqlCommand("select * from UserInfo where UserId = @UserId", con);
    cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = userId;
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    adapter.Fill(ds, "userInfo");
    DataTable dt = ds.Tables[0];
    DataRow row = dt.Rows[0];
    cmd.Dispose(); 
    #endregion

    con.Close();
    return rowNumber;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

The difference between parameterized query and ordinary query is in the writing of sql statement,
ordinary query query:
"select * from UserInfo where UserId = " + userId
parameterized query:
"select * from UserInfo where UserId = @UserId";
cmd.Parameters. Add();
ordinary statement insertion:
string.Format("insert into UserInfo values({0},{1},{2},{3})",userId,userName,"getdate()",gender);
parameters Parameterized insert:
"insert into UserInfo values(@userId,@userName,getdate(),@gender)";
cmd.Parameters.Add()
parameterized query is marked with @+field name to indicate that something is to be entered here, and then These tags are given concrete types and assigned values ​​through cmd.Parameters.Add().

Stored procedure:

Create insert stored procedure code

CREATE PROCEDURE [dbo].[Proc_InsertUserInfo]
    @UserId int,
    @UserName nvarchar(20),
    @AddTime datetime,
    @Gender nvarchar(2)
AS
BEGIN
    SET NOCOUNT ON;
    insert into dbo.UserInfo values(@UserId,@UserName,@AddTime,@Gender)

END
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Create select stored procedure code

ALTER PROCEDURE [dbo].[Proc_SelectUserInfo]
    @UserId int
AS
BEGIN
    SET NOCOUNT ON;
    SELECT * from dbo.UserInfo where UserId=@UserId
END
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Execute the stored procedure code:

public static int Insert(string userId,string userName,string gender)
{
    int rowNumber = -100;
    string strConnection = ConfigurationManager.ConnectionStrings["connString"].ToString();
    SqlConnection con = new SqlConnection(strConnection);
    con.Open();

    #region 存储过程插入
    SqlCommand cmd1 = new SqlCommand("Proc_InsertUserInfo", con);
    cmd1.CommandType = CommandType.StoredProcedure;
    cmd1.Parameters.Add("@UserId", SqlDbType.Int).Value = userId; ;
    cmd1.Parameters.Add("@UserName", SqlDbType.NVarChar, 20).Value = userName;
    cmd1.Parameters.Add("@AddTime", SqlDbType.DateTime).Value = DateTime.Now.ToString();
    cmd1.Parameters.Add("@Gender", SqlDbType.NVarChar, 2).Value = gender == "1" ? "男" : "女";
    rowNumber = cmd1.ExecuteNonQuery();
    cmd1.Dispose(); 
    #endregion

    #region 存储过程查询
    SqlCommand cmd = new SqlCommand("Proc_SelectUserInfo", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = userId;
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    rowNumber = adapter.Fill(ds, "userInfo");
    DataTable dt = ds.Tables[0];
    DataRow row = dt.Rows[0];
    #endregion

    con.Close(a);
    return rowNumber;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

Insert code in stored procedure:
insert into dbo.UserInfo values(@UserId,@UserName,@AddTime,@Gender)
Query code in stored procedure:
select * from dbo.UserInfo where UserId=@UserId
Call stored procedure method:
cmd .CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add();
If the execution result returns a data table, it can still be obtained with SqlDataAdapter and DataSet, which is no different from ordinary Sql statements, except that the stored procedure needs to declare variables first It can be used in Sql statements, which saves the compilation time of Sql statements and improves efficiency.

in conclusion

Parameterized queries and stored procedures are roughly the same in the way they are declared and used, with three differences:

  • The parameterized query directly uses @+ parameter name as the parameterized mark, the same is true for the stored procedure, but the type of the mark must be declared in the stored procedure before it can be used.
  • Parameterized query SqlCommand cmd = new SqlCommand("Sql statement", con);
    stored procedure query SqlCommand cmd = new SqlCommand("stored procedure name", con);
  • When calling a stored procedure, it is necessary to indicate that the stored procedure is used here, cmd.CommandType =CommandType.StoredProcedure;,
    the default is CommandType.Text

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325479936&siteId=291194637