how do i link mssql to android studios? - sql-server

Please bear with, I have a little experience in SQL but otherwise I am a complete newbie when it comes to programming/coding.
I have a database with Microsoft SQL server and I have downloaded Android studios.
In short I want to create a basic app that can have the ability to show data as well as update tables from my database. (app won't be a problem)
The question is, what would be the 'best' way to do to link database to my app? Bearing in mind I am not at a great technical level at the moment
I have been informed that linking to the database to the app directly may pose security risks but other than that I am a bit lost at how to get the information I need to get started...
Any information you can chuck my way will be greatly appreciated!!

First, you need to download JTDS drivers https://sourceforge.net/projects/jtds/
If you are not sure about how to set up watch this video as a reference https://youtu.be/UXy_phw5Psg.
To add jar files to your android studio:
Right-click on app > New > Module.
A window will open where you can find jar files when you scroll down.
Select the widget another window will open, find the location of your jar and select.
Finish. That is it you can start creating projects with SQL server after the build is finished.
Now after adding JTDS, you have to Add This Line In Your App Gradle File, x.x.x is the version of JTDS that you downloaded
dependencies{
implementation project(':jtds-x.x.x')
}
Now we are going to make a java class to connect SQL server and android studio. Remember this class is the heart of your every android project with SQL server.
Use Imports Correctly.
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
// Your IP address must be static otherwise this will not work. You //can get your Ip address
//From Network and security in Windows.
String ip = "000.000.000.00";
// This is default if you are using JTDS driver.
String classs = "net.sourceforge.jtds.jdbc.Driver";
// Name Of your database.
String db = "MyDB";
// Userame and password are required for security.
so Go to sql server and add username and password for your database.
String un = "username";
String password = "passw0rd";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL;
try {
Class.forName(classs);
ConnURL = "jdbc:jtds:sqlserver://" + ip + ";"
+ "databaseName=" + db + ";user=" + un + ";password="
+ password + ";";
conn = DriverManager.getConnection(ConnURL);
}
catch (SQLException se)
{
Log.e("safiya", se.getMessage());
}
catch (ClassNotFoundException e) {
}
catch (Exception e) {
Log.e("error", e.getMessage());
}
return conn;
}
}
Strict Mode:
StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them.
StrictMode is most commonly used to catch accidental disk or network access on the application’s main thread, where UI operations are received and animations take place. Keeping disk and network operations off the main thread makes for much smoother, more responsive applications.
Orignal link to this is guide is https://life-news.blog/2018/09/24/connect-sql-server-with-android-application-jdbc-driver-integration/

Related

Connection String not found Azure Data Studio to VS2022 - Mac

I am trying to setup my uni work (which is windows based) onto my mac. I have a docker container running with AzureSQLEdge, which I have connected to my Azure Data Studio and can run queries no problem. However in VS2022 trying to set up the connection to the database in Azure Data Studio.
At the moment I am just trying to get some IDs printed to the page (we are using #razor)
#using WebMatrix.Data
#{
ViewBag.Title = "About Us";
var db = Database.Open("AmazonOrders");
var select = "SELECT * FROM Customers";
var data = db.Query(select);
}
<h2 class="text-center">#ViewBag.Title</h2>
<h3>#ViewBag.Message</h3>
<p>Use this area to provide additional information</p>
#foreach (var row in data)
{
#row.customerID
}
My connection string in appsettings.json is:
"AllowedHosts": "*",
"ConnectionStrings": {
"AmazonOrders": "Server=tcp:127.0.0.1,1433;Database=AmazonOrders;User=sa;Password=SQLserver123!;"
}
However I am getting this error message when I load the page:
InvalidOperationException: Connection string "AmazonOrders" was not found.
Setting up the connection string is all the windows users have to do, they have a local version of the database in their project solution. Any help is appreciated, the resources online are more about creating db contexts which I would prefer to avoid if possible, and just connect directly to my database on docker/azure data studio.
edit
Here is the full appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"AmazonOrders": "Server=tcp:127.0.0.1,1433;Database=AmazonOrders;User=sa;Password=SQLserver123!;"
}
}
#using WebMatrix.Data
This is an old data access library intended solely for use with ASP.NET Web Pages, which is a pretty ancient (and virtually obsoleted) web development framework that targets the full .NET Framework. As such, it knows nothing about appsettings.json files which were introduced in .NET COre. The primary configuration mechanism for Web Pages is a web.config file and that's where this library looks for a connection string.
If I were you, I would remove WebMatrix.Data from your project (assuming it is actually a Razor Pages app, not Web Pages) and use Entity Framework Core instead. If it is a Web Pages app and that's the framework you want to work with, remove the appsettings.json file and add a connection string to the web.config file: https://www.connectionstrings.com/store-connection-string-in-webconfig/

Mirth- Database writer error

I am trying to create a channel to write to a database from HTTP source.
I have made two destinations both to same database. One destination writes via JavaScript and the other with SQL.
The data gets written to database in the first destination(the JavaScript one) but not through the second(SQL). I am not able to get the tables through "Insert" button also. It gives the following error:
Someone please give me the solution to set up database connection without any flaw. Please note that the database is secured one in AWS instance.
To connect to database via javascript, you will need to select "Yes" under the option to use javascript. Then your connector will look something like this:
var dbConn;
try {
dbConn = DatabaseConnectionFactory.createDatabaseConnection('net.sourceforge.jtds.jdbc.Driver','ServerURL','Username','Password');
// You may access this result below with $('column_name')
return result;
} finally {
if (dbConn) {
dbConn.close();
}
}
Note that you can click on the "generate" button and this template will be created for you in the javascript window.
Based on the information you have given, I am not sure that your method/syntax is the cause to your error. Can you verify that your database driver jar file is located in your installation? (Mine is located at "...\Mirth Connect\server-lib\database"

not getting any error when serilog is not able to insert data in sql server

I am using serilog as logging framework in .net core 2.0 project and i am trying to store the logs in sql server but serilog is not storing any data in database and it is not even returning error.
can any one help how to resolve this issue and is it possible to add file approach to store logs when database fails to store
Serilog.Debugging.SelfLog
You can use the SelfLog property to tell serilog where to log it's own errors (all of us have had to debug the logger at some point).
Sample Code
Because I hate providing an answer without sample code that others might find useful ... here is the code we use to "initialize" our logger (including serilog and seq -- a great combo for generating centralized logs that the devops team can monitor).
Serilog.Debugging.SelfLog.Enable(Console.Error);
ILoggerFactory factory = new LoggerFactory();
factory.AddConsole();
factory.AddDebug();
var env = "PROD"; //MyEnvironment: PROD, STAGE, DEV, ETC
var seqLogger = new LoggerConfiguration()
.MinimumLevel.Information()
.Enrich.FromLogContext()
.Enrich.WithProperty("Environment", env)
.WriteTo.Seq(
"logserveraddress",
Serilog.Events.LogEventLevel.Verbose,
1000,
null,
"LogServerApiKey")
);
if (env.ToLower() == "prod") { seqLogger.MinimumLevel.Warning(); }
factory.AddSerilog(seqLogger.CreateLogger());
}
return factory.CreateLogger("NameThisLogInstaceSomethingUseful");

Play Siena failing to connect to MySQL on GAE

I am using play framework 1.2.7, gae module 1.6.0 and siena module 2.0.7 (also tested 2.0.6). This is a simple project that should run in play deployed on App Engine and connect to a MySQL database in Google Cloud SQL. My project runs fine locally but fails to connect to the database in production. Looking at the logs it looks like it is using the postgresql driver instead of the mysql one.
Application.conf
# db=mem
db.url=jdbc:google:mysql://PROJECT_ID:sienatest/sienatest
db.driver=com.mysql.jdbc.GoogleDriver
db.user=root
db.pass=root
This is the crash stack trace
play.Logger niceThrowable: Cannot connected to the database : null
java.lang.NullPointerException
at com.google.appengine.runtime.Request.process-a3b6145d1dbbd04d(Request.java)
at java.util.Hashtable.put(Hashtable.java:432)
at java.util.Properties.setProperty(Properties.java:161)
at org.postgresql.Driver.loadDefaultProperties(Driver.java:121)
at org.postgresql.Driver.access$000(Driver.java:47)
at org.postgresql.Driver$1.run(Driver.java:88)
at java.security.AccessController.doPrivileged(AccessController.java:63)
at org.postgresql.Driver.getDefaultProperties(Driver.java:85)
at org.postgresql.Driver.connect(Driver.java:231)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at play.modules.siena.GoogleSqlDBPlugin.onApplicationStart(GoogleSqlDBPlugin.java:103)
at play.plugins.PluginCollection.onApplicationStart(PluginCollection.java:525)
at play.Play.start(Play.java:533)
at play.Play.init(Play.java:305)
What is going on here? I am specifying the correct driver and url schema and it's using postgresql driver. Google Cloud SQL API access is enabled, the app is allowed to connect to the mysql instance, I am not using db=mem, ... I am stuck and can't figure out how to move forward! :-((
UPDATE: I thought I found the solution, but that was not the case. If I keep the %prod. prefix and create a war normally (or just don't define any DB properties), then the application will use Google DataStore instead of the Cloud SQL. If I create the war file adding --%prod at the end (or just delete the %prod. prefix in the application.conf), then it will keep failing to connect to the database showing the same initial error.
Any ideas please?
After being stuck for so long on this I just found the solution in no time after posting the question. Quite stupid actually.
The production environment properties in the application.conf file must be preceded by %prod. so the database config should read
%prod.db.url=jdbc:google:mysql://PROJECT_ID:sienatest/sienatest
%prod.db.driver=com.mysql.jdbc.GoogleDriver
%prod.db.user=root
%prod.db.pass=root
And everything runs fine.
EDIT: This is NOT the solution. The problem went away, but the app is using the DataStore instead of the Cloud SQL
At the end I ended doing a slight modification in play siena module source code and recompiling it.
In case anyone is interested, you will need to remove/comment/catch exception in this code around line 97 in GoogleSqlDBPlugin class:
// Try the connection
Connection fake = null;
try {
if (p.getProperty("db.user") == null) {
fake = DriverManager.getConnection(p.getProperty("db.url"));
} else {
fake = DriverManager.getConnection(p.getProperty("db.url"), p.getProperty("db.user"), p.getProperty("db.pass"));
}
} finally {
if (fake != null) {
fake.close();
}
}
For some reason the connection fails when initiated with DriverManager.getConnection() but it works when initiated with basicDatasource.getConnection(); which apparently is the way used by the module in the rest of the code. So if you delete the above block, and recompile the module everything will work as expected. If you are compiling with JDK 7, you will also need to implement public Logger getParentLogger() throws SQLFeatureNotSupportedException in the ProxyDriver inner class at the end of GoogleSqlDBPlugin file.
Strangely, I digged into the DriverManager.getConnection() and it looked like some postgresql driver is registered somehow, because otherwise I can't see why DriverManager.getConnection() would call to org.postgresql.Driver.connect().

Web Security Membership & Database Permissions

I am trying to deploy my site to 123reg but having difficulty with database permissions. I see other people have similar issues, but they all seem to be using entity framework with DBContexts, whereas I am not (I don't think).
I am using the Web.Security.Membership.CreateUser method. All of the database tables are set up. My connectionstring is almost certainly correct as I have the same setup on a different hosting provider which works perfectly. The site can read from the database but fails when it tries to write.
When the method is invoked, I get the following error.
CREATE DATABASE permission denied in database 'master'.
Is there anyway to stop the DefaultMembershipProvider from trying to create the database or tell it exactly where it is?
<add name="Simple.Data.Properties.Settings.DefaultConnectionString" connectionString="Server=ATLAS-SQL-07;Database=mydatabasename;User ID=myuserid;Password=xxxxxx;" />
I'm using Simple.Data (as can be seen the from name of the connectionstring). Maybe this is causing it problems. I don't see why it works flawlessly on my Netcetera hosting though?
To test it out further, I published the MVC4 sample web application to 123reg and pointed to the same database, it had exactly the same issue.
I had a similar problem with 123-reg; and a number of other issues. I found the best approach
was to blank out the call to create database and import a working database, (with one user in it). Make sure you do the import file as ANSI, otherwise you get a random character inserted on the import.
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer(null);
try
{
/*
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}*/
WebSecurity.InitializeDatabaseConnection("TobaContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
I have had a number of problems with 123-reg - some of it my fault - some of it theirs I think.
As a heads up on membership - at the moment I am getting problems with the RequireHTTPS attribute. It appears to cause a
'too many server redirects' issue. Yet I thought that attribute was suppose to work out of the box.
Good luck, hope been of some help,
Dave

Resources