简体   繁体   English

如何在Java(和SQL Server)中使用Statement.execute()更改数据库架构?

[英]How can I change the database schema using a Statement.execute() in Java ( and SQL Server)?

I need to execute a SQL Server system stored procedure, programmatically, and since it executes in the current schema, I need to change it on the fly. 我需要以编程方式执行SQL Server系统存储过程,由于它是在当前架构中执行的,因此我需要即时对其进行更改。

Like this 像这样

Statement st = connection.createStatement(); 语句st = connection.createStatement(); st.execute("EXEC SP_ADDUSER ' ', ' '"); st.execute(“ EXEC SP_ADDUSER'',''”);

But SP_ADDUSER only executes on the current schema set for the connection, so if I wanted to create users in various schemas, I'd need to change it, and that's what I am looking for. 但是SP_ADDUSER仅在连接的当前模式集上执行,因此,如果我想在各种模式下创建用户,则需要对其进行更改,这就是我想要的。

I don't believe it's possible to change which database a connection points to. 我不认为可以更改连接指向的数据库。

You'll probably need to create a separate DataSource/Connection for each database (schema). 您可能需要为每个数据库(架构)创建一个单独的DataSource / Connection。

EXEC <DatabaseName>..sp_adduser can be run from a connection to any database (even master , say). EXEC <DatabaseName>..sp_adduser可以通过连接到任何数据库(甚至是master )运行。 The connection will not be affected. 连接不会受到影响。

For instance, the following appears to work fine on my system: 例如,以下内容在我的系统上似乎可以正常工作:

USE master
EXEC sp_addlogin 'test1'
EXEC SandBox..sp_adduser 'test1'

The same things works fine through the client. 通过客户端,同样的事情也可以正常工作。 Is your client connection altering your SQL? 您的客户端连接是否改变了您的SQL?

using System;
using System.Data.SqlClient;

namespace TestUse
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection cn = new SqlConnection("Server=(local);Database=master;Trusted_Connection=True;");
            cn.Open();
            SqlCommand cmd = new SqlCommand("USE master; EXEC sp_addlogin 'test1'; EXEC SandBox..sp_adduser 'test1'", cn);
            cmd.ExecuteNonQuery();
            cn.Close();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM