Is there any way I can execute these queries with jpa? - sql-server

Is it possible to execute this query in jpa because the only options I see are .getSingleResult(); or .getResultList(); which both will throw exception since this query won't return any result.
Is there any way I can execute these queries with jpa?
And the reason I want to do it with jpa is because the entityManager already has the connection details and I don't want to create a special connection just for this query.
Query LoginkrijoQuery=em.createNativeQuery("USE MDAfondation ;"+
"CREATE LOGIN "+username+" WITH password= '"+password+"',DEFAULT_DATABASE = MDAfondation,DEFAULT_LANGUAGE = english,CHECK_EXPIRATION = OFF ;");
LoginkrijoQuery.getSingleResult();
well I tried it like this
em.getTransaction().begin();
em.createNativeQuery("USE MDAfondation;\n "+
"CREATE LOGIN "+username+" WITH password= '"+password+"',DEFAULT_DATABASE = MDAfondation,DEFAULT_LANGUAGE = english,CHECK_EXPIRATION = OFF;\n"+
"USE MDAfondation;\n" +
"CREATE USER "+username+" FOR LOGIN "+username+";\n"+
"USE MDAfondation;\n" +
"sp_addrolemember 'stafi', '"+username+"';\n");
em.getTransaction().commit();
Now it doesn't throw any exception but the query is never executed because when I check in SQL Server the login , user never get created

Related

System.Data.SqlClient.SqlException: 'Could not find stored procedure 'Usp_GetUserName_By_UserID'.'

I am running into this exception when I try to login, the user is not yet registered in the database. I am testing some scenarios of my logic, if not registered. Do I need to create a stored procedure for that table from the database?
public string GetUserName_By_UserID(string UserId)
{
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyString"].ToString()))
{
var para = new DynamicParameters();
para.Add("#UserId", UserId);
return con.Query<string>("Usp_GetUserName_By_UserID", para, null, true, 0, CommandType.StoredProcedure).SingleOrDefault();
}
}
Before calling a procedure from your MVC application please check that same one is existing in your Database also otherwise getting this kinds of errors.

pyodbc will only execute commands when querying the database specified in the connection string

conn = pyodbc.connect(r'DRIVER={SQL Server Native Client 11.0};SERVER=localhost\<redacted>;DATABASE=master;UID=<redacted>;PWD=<redacted>')
cursor = conn.cursor()
query = """SELECT <redacted> FROM <redacted> WHERE <redacted>"""
row = cursor.execute(query).fetchone()
dummyName = row[0]
cursor.close()
cursor = conn.cursor()
query = """SELECT <redacted> FROM <redacted> WHERE <redacted>"""
print query
row = cursor.execute(query)
print row.fetchone()
This code properly connects to the db and executes the first query on the first db. However, when it executes the second query on the other db, it doesn't return any data and I get a popup window saying python.exe has stopped working when I try to fetch any rows, after which my program crashes. I checked and the query I'm trying to execute is a valid query that works properly from the master db and from the same account I'm connected to in the code.
The problem was we were using an old version of pyodbc. I updated it to the new version and now it works perfectly.

How to create a Database user in Entity Framework

Been working on my first Entity Framework project. As part of the project I am going to be creating a number of SSRS reports. In order to connect to the database I need to have a Reports user that will only access to the specific database on the server. In the past i have always written a script to add Database users but I want to know is there a way that i can do this using Entity Framework instead?
Assuming your user already has a login defined at the SQL Server level (Security > Logins), you can call the following method from your DB initializer seed method to add the user to the database:
private void AddDbUser(MyDataContext myDB)
{
string accountDomainName = "AccountDomainName"; // replace with user's login domain
string accountLoginID = "AccountLoginID"; // replace with user's login ID
string sql =
"USE [MyDB]" +
"CREATE USER [MyNewUser] FOR LOGIN [" + accountDomainName + "\\" + accountLoginID + "]" +
"ALTER AUTHORIZATION ON SCHEMA::[db_datareader] TO [" + accountLoginID + "]" +
"ALTER AUTHORIZATION ON SCHEMA::[db_datawriter] TO [" + accountLoginID + "]" +
"EXEC sp_addrolemember N'db_datawriter', N'" + accountLoginID + "'" +
"EXEC sp_addrolemember N'db_datareader', N'" + accountLoginID + "'";
myDB.Database.ExecuteSqlCommand(sql);
}
The exact SQL needed is dependent on your configuration. To have SQL Server generate the SQL for your scenario, you could open the add user dialog in SSMS (Database > Users > New User...), fill out the fields, and click the "Script" button at the top instead of hitting OK at the bottom. Note that any "GO" lines will need to be removed from the generated script before pasting it into the method above.
You would need to tell EF to use the appropriate stored procedures to do so. You could also wrap these up in a sproc of your own that wraps the relevant commands. There is no native "CreateReportsUser" type method within EF that I know of.
Edit: I probably should have provided this reference to be a "complete" answer. Apologies.
Here's how you can do what I recommend: How to call Stored Procedure in Entity Framework 6 (Code-First)?

Azure SQL server error Statement 'RECEIVE MSG' is not supported in this version of SQL Server

I have used SQLdependency with SignalR to show alerts to users.. The code is as follows:
public IEnumerable<AlertInfo> GetData(long UserId)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["yafnet"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [AlertID],[AlertNote],[AlertDetails],[AlertDate],[Location]
FROM [dbo].[Alerts] where [UserID]=" + UserId + " AND [IsViewed]=0", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["yafnet"].ConnectionString);
SqlDependency.Start(ConfigurationManager.ConnectionStrings["yafnet"].ConnectionString);
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new AlertInfo()
{
AlertID = x.GetInt64(0),
AlertNote = x.GetString(1),
AlertDetails = x.GetString(2),
AlertDate = x.GetDateTime(3),
Location = x.GetString(4)
}).ToList();
}
}
}
It is working fine on localhost. But after uploading to Azure server, this method throws the following error:
Message":"An error has occurred.","ExceptionMessage":"Statement 'RECEIVE MSG' is not supported
in this version of SQL Server.","ExceptionType":"System.Data.SqlClient.SqlException","StackTrace":"
\r\nServer stack trace: \r\n at System.Data.SqlClient.SqlConnection.OnError(SqlException exception
, Boolean breakConnection, Action`1 wrapCloseInAction)
What could be the issue?
Actually your SQL Server database must have is_broker_enabled = 1.
You need to check whether it's enabled or not.
To verify this, use the command SELECT name, is_broker_enabled FROM sys.databases.
If your database shows result "1" it's okay and if "0" then you must enable it using this command ALTER DATABASE yourdb SET ENABLE_BROKER.
But the bad news is Azure SQL database shows it enabled but it no longer supports is_broker_enabled.
To do this, you need to install the full instance of SQL Server to Azure VM.

Vb.Net & SQL Server Express : Create User for login throws error

We attached the database PStorage to the server.
Then I tried to create the login & user using the following code:
Dim con As New SqlConnection
Dim query As SqlCommand
con.ConnectionString = "Server=(LocalHost);Data Source=LocalHost\SQLEXPRESS;Database=PSTORAGE;Integrated Security=TRUE"
con.Open()
query.CommandText = "IF NOT EXISTS(SELECT [LoginName] FROM MASTER.DBO.SYSLOGINS WHERE [Name]='UserCP') CREATE LOGIN UserCP WITH PASSWORD='CPPassword'"
query.ExecuteNonQuery()
query.Dispose()
query.CommandText = "IF NOT EXISTS(SELECT [Name] FROM SYS.DATABASE_PRINCIPALS WHERE [Name]='CPUser') CREATE USER CPUser FOR LOGIN UserCP"
query.ExecuteNonQuery() 'This line is throwing the error -> Login Failed for the User 'UserCP'.
query.Dispose()
The error we are getting after executing the second query is
Login failed for the user 'UserCP'
While attaching the database the same error occurs. Then we had to use sqlCmd.
In all the systems this method works fine. But in one of our customers system this problem occurs. What might be the reason?
After a lot of tries we could come to know that the folder was compressed [All the file names were in blue colour]. Since the database files were inside the compressed folder- none of the operations could be done on them perfectly.
Right click on the database folder, Press on Properties
Press on Advanced
Untick the Compress contents to save disk space
Save the changes made

Resources