How to form connection between HSQLDB and C# .net? - hsqldb

How to form connection between HSQLDB and C# .net ? I have already looked at SharpHSQL and H2Sharp but not able to connect the HSQLDB.

try like this:
Make sure you've already add hsqldb.dll, IKVM.OpenJDK.Core.dll, IKVM.OpenJDK.Jdbc.dll as reference.
If you don't have the IKVM library, you can download here.
At your C#:
using java.sql; //add this.
for create a connection:
private Connection GetConnection()
{
DriverManager.registerDriver(new org.hsqldb.jdbcDriver());
Connection conn = DriverManager.getConnection("jdbc:hsqldb:hsql://[host]/[db name]", "[username]", "[password]");
return conn;
}
how to use it:
public void LoadSetting(String userId)
{
Connection conn = null;
try
{
//Connect it!
conn = GetConnection();
string query = "SELECT A.* FROM table A";
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
//Get Query Result
Console.WriteLn(rs.getString("COL1"));
Console.WriteLn(rs.getString("COL2"));
}
}
//Close the Connection
finally
{
if (conn != null && !conn.isClosed())
{
conn.close();
conn = null;
}
}
}
Hope this help.
Cheers...

Basic steps:
Download IKVM.NET and HyperSQL (=HSQLDB) driver.
Convert HSQLDB Java driver to .NET DLL using IKVM.NET to create a hsqldb.dll
Add compile time dependencies to your C# project:
hsqldb.dll
IKVM.OpenJDK.Core.dll
IKVM.OpenJDK.Jdbc.dll
Add runtime dependencies when running your C# program:
IKVM.OpenJDK.Localedata.dll
IKVM.OpenJDK.Text.dll
IKVM.OpenJDK.Util.dll
IKVM.Runtime.dll
Add connection string to your app.config :
<configuration>
<connectionStrings>
<add name="HyperSQL"
connectionString="jdbc:hsqldb:hsql://localhost:9999/xdb;user=SA;password=;" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
C# code:
using System;
using System.Configuration;
namespace HyperSQL
{
class Program
{
readonly static string CONNECTION_STRING = ConfigurationManager.ConnectionStrings["HyperSQL"].ConnectionString;
const string SQL = "SELECT * FROM customer";
static void Main(string[] args)
{
java.sql.DriverManager.registerDriver(new org.hsqldb.jdbcDriver());
using (java.sql.Connection conn = java.sql.DriverManager.getConnection(CONNECTION_STRING))
{
java.sql.PreparedStatement ps = conn.prepareStatement(SQL);
using (java.sql.ResultSet rs = ps.executeQuery())
{
while (rs.next())
{
Console.WriteLine($"ID={rs.getInt("id")}");
Console.WriteLine($"NAME={rs.getString("name")}");
Console.WriteLine($"AGE={rs.getInt("age")}");
Console.WriteLine($"ADDRESS={rs.getString("address")}");
Console.WriteLine($"SALARY={rs.getInt("salary")}");
Console.WriteLine("------------------");
}
}
}
Console.ReadLine();
}
}
}
Here my detailed tutorial how to connect to HyperSQL from C#

Related

Unable to connect Azure Function App with Database (using .net core 2.1)

Please note (Environment):
Function App: Version 2,
Target Framework: .Net Core 2.1
I am developing a Function App, that will work like Web Api. This Function App will return the data from database tables, also it'll manipulate files in Azure storage(Blob). But I am stuck as I am unable to create ConnectionString from local.settings.json file. Ideally the connection string should be created by default as I followed some tutorials & no where mentioned any extra steps to create default connectionstring value, just need to create it in local.settings.json file.
following is my local.settings.json file content:-
{
"ConnectionStrings": {
"mycs": "data source=servername;initial catalog=dbname;user id=XXXX;password=XXXX;MultipleActiveResultSets=True;"
},
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"mycs": "data source=servername;initial catalog=dbname;user id=XXXX;password=XXXX;MultipleActiveResultSets=True;"
}
}
following is my HttpTrigger file:
namespace my_api
{
public class myDataContext : DbContext
{
public myDataContext() : base(GetConnectionString()) { }
private static string GetConnectionString()
{
const string providerName = "System.Data.SqlClient";
const string metadata = #"res://*/MYDB.csdl|res://*/MYDB.ssdl|res://*/MYDB.msl";
try
{
string connectString = ConfigurationManager.ConnectionStrings["mycs"].ToString();
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(connectString);
// Set the properties for the data source.
//sqlBuilder.IntegratedSecurity = true;
sqlBuilder.MultipleActiveResultSets = true;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// Set the Metadata location.
entityBuilder.Metadata = metadata;
return entityBuilder.ConnectionString;
}
catch { }
var connectionstring = Environment.GetEnvironmentVariable("mycs");
return connectionstring;
}
public DbSet<flowerset> flowersets
{
get;
set;
}
}
}
Following is the code for :
namespace my_api
{
public static class helpService
{
[FunctionName("helpService_get")]
public static async Task> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log, ExecutionContext context)
{
log.LogInformation("C# HTTP trigger function processed a request helpService_get).");
try {
int page = 0;
int pageSize = 20;
myDataContext entity = new myDataContext();
if (page == 0 && pageSize == 0)
{
return entity.helpsets.ToList();
}
if (pageSize <= 0) { pageSize = 20; }
entity.helpsets.OrderByDescending(x => x.id).Skip((page - 1) * pageSize).Take(pageSize).ToList();
}
catch (Exception exx) {
log.LogInformation("Exception changed (helpService_get): "+exx.Message);
}
return null;
}
}//End of Class
}//End of Namespace
I am getting following error on line entity.helpsets.OrderByDescending(x => x.id).Skip((page - 1) * pageSize).Take(pageSize).ToList();:
Unable to determine the provider name for provider factory of type 'System.Data.SqlClient.SqlClientFactory'. Make sure that the ADO.NET provider is installed or registered in the application config.
According to my test, we can use System.Data.SqlClient to connect Azure SQL in Azure function V2.0. For example
Create an Azure Function with Visual Studio 2019
Install System.Data.SqlClient package(the version I sue is 4.5.1)
Develop the function
local.settings.json file content
"ConnectionStrings": {
"mycs": "Data Source="";Initial Catalog=DotNetAppSqlDb20190826105048_db;User Id="";Password="" "
},
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
Code
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
try
{
var connectionstring = System.Environment.GetEnvironmentVariable($"ConnectionStrings:mycs"); ;
using (SqlConnection connection = new SqlConnection(connectionstring))
{
connection.Open();
log.LogInformation(" sql login success");
StringBuilder sb = new StringBuilder();
sb.Append("select * from dbo.Todoes");
String sql = sb.ToString();
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
log.LogInformation("{0} {1}", reader.GetInt32(0), reader.GetString(1));
}
}
}
connection.Close();
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
For more details, please refer to the document

Using SQL Dependency with Azure

In my Local DB Sql Dependency works fine, but when i migrate to an Azure Database is not work.
I check if service broker is enabled, and it is activated.
This is the error:
Statement 'RECEIVE MSG' is not supported in this version of SQL Server
This is my code:
public class Program
{
static void Main(string[] args)
{
SqlClientPermission permission = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
if (SolicitarNotifications())
{
string con = "Server=tcp:xxxxx.database.windows.net,0000;Initial Catalog=TestSQLDependendcy;Persist Security Info=False;User ID=xxxx;Password=xxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
SqlConnection conn = new SqlConnection(con);
SqlDependency.Start(con);
Console.WriteLine("Empezando a escuchar");
GetAlerts();
Console.WriteLine("Presiona enter para salir");
Console.ReadLine();
Console.WriteLine("Deteniendo la escucha...");
SqlDependency.Stop(con);
}
else {
Console.WriteLine("No tienes permitido solicitar notificaciones");
}
}
public static void GetAlerts()
{
try
{
using (SqlConnection con = new SqlConnection("Server=tcp:xxxxx.database.windows.net,0000;Initial Catalog=TestSQLDependendcy;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"))
{
SqlCommand cmd = new SqlCommand("Select Correo, Nombre From TestNombre", con);
cmd.CommandType = CommandType.Text;
cmd.Notification = null;
cmd.Dispose();
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(OnDataChange);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
{
while (dr.Read())
{
if (dr.HasRows)
{
using (MailMessage mm = new MailMessage())
{
//Send Mails
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
private static void OnDataChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = sender as SqlDependency;
dependency.OnChange -= new OnChangeEventHandler(OnDataChange);
GetAlerts();
}
}
How to run this service in Azure SQL Database?
Currently, Azure SQL does not support Service Broker.
Find RECEIVE statement supported versions at https://learn.microsoft.com/en-us/sql/t-sql/statements/receive-transact-sql?view=sql-server-2017, which states Azure SQL does not support it.
In addition, this documentation https://learn.microsoft.com/en-us/azure/sql-database/sql-database-features provides a great feature comparison documentation between SQL Server, Azure SQL and Managed Instances. Note that Manage Instance supports Service Broker with some differences. I'd recommend signing up for the preview and trying it out.

Create Connection String during installation

I have a Windows Forms application. I want to create a setup file for this application. I used Visual Studio 2012 and SQL Server 12.
I want this setup to work in every new environment.
So, how do I make this connection string dynamic? Can I create a connection string after installation and make it available for every form to access, like in my local machine?
Any kind of source code, video links, explanations or examples will be a great help for me.
I propose to search on the machine for instances of the SQL server, and then in every instance search for the databases. You could setup some logic for example if only one instance is found, and on this instance only database with specific name exists then use this database, but if two or more instances are found, or different database name then preferred is found, show window to user where he can choose the right one.
To find Database instance you could use following method:
private static DataRowCollection SQLDataServers()
{
System.Data.Sql.SqlDataSourceEnumerator instance = System.Data.Sql.SqlDataSourceEnumerator.Instance;
DataTable dt = instance.GetDataSources();
if (dt.Rows.Count>0)
{
return dt.Rows;
}
throw new Exception("No SQL Instance Found");
}
To find tables in the database you can use following method:
private static List<string> GetDatabases(string conString)
{
List<string> list = new List<string>();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
To generate connection string you can use nuget package or following methods:
public static string GetSqlDataSourceConnectionString(string dataSource)
{
return GetSQLDataSource(dataSource).ToString();
}
private static SqlConnectionStringBuilder GetSQLDataSource(string dataSource)
{
var r = GetDataSource(dataSource).AddIntegratedSecurity();
return r;
}
private static SqlConnectionStringBuilder GetDataSource(string dataSource)
{
SqlConnectionStringBuilder sqlBuilder = new
SqlConnectionStringBuilder();
sqlBuilder.DataSource = dataSource;
return sqlBuilder;
}
private static SqlConnectionStringBuilder AddIntegratedSecurity(this SqlConnectionStringBuilder connectionStringBuilder)
{
connectionStringBuilder.IntegratedSecurity = true;
return connectionStringBuilder;
}
The method which connects all this elements can be as following:
static void Main(string[] args)
{
var servers=SQLDataServers();
foreach (DataRow item in servers)
{
string serverName = string.Format($"{item.ItemArray[0].ToString()}\\{item.ItemArray[1].ToString()}");
var connectionString = GetSqlDataSourceConnectionString(serverName);
var listOfDB=GetDatabases(connectionString);
}
}

RavenB select database

var store = new DocumentStore()
{
Url = #"http://localhost"
};
store.Initialize();
Blog blog = new Blog()
{
Title = "Hello RavenDB",
Category = "RavenDB",
Content = "This is a blog about RavenDB",
Comments = new BlogComment[]{
new BlogComment() { Title = "Unrealistic", Content= "This example is unrealistic"},
new BlogComment() { Title = "Nice", Content= "This example is nice"}
}
};
using (IDocumentSession session = store.OpenSession())
{
session.Store(blog);
session.SaveChanges();
}
The above code saves data to the default database. (It is a web application.) But I want it save data to another database that I created the raven management studio (web page). Where do i specify the database name? Also please tell me how I can save the connection string with the database name in the config file. This is how I would save it to config file without the database name
<connectionStrings>
<add name="Local" connectionString="DataDir = ~\Data"/>
<add name="Server" connectionString="Url = http://localhost:8080"/>
</connectionStrings>
All of your questions are explained in the documentation:
new DocumentStore
{
ConnectionStringName = "Local"
}
<connectionStrings>
<add name="Local" connectionString="DataDir=~\Data;Database=MyDatabaseName"/>
<add name="Server" connectionString="Url=http://localhost:8080;Database=MyDatabaseName"/>
</connectionStrings>
The other answers are ok, but for efficiency you really only want one instance of DocumentStore for your application, unless you are running multiple Raven servers and then it would be acceptable to have one per server.
If you are just connecting to different databases on the same server, you should use:
var store = new DocumentStore(...your connection string or inline options...);
using (var session = store.OpenSession("the database name")
{
...
}
You can keep your connection strings data as you shown, best with the databases names at the end:
<connectionStrings>
<add name="Core" connectionString="Url=http://localhost:8082/databases/Core"
providerName="My primary database." />
<add name="Backup" connectionString="Url=http://localhost:8082/databases/Backup"
providerName="My backup stuff." />
</connectionStrings>
Next you can implement singleton class which will keep all your handlers for defined sources, for example:
public class DocumentStoreProvider : IDocumentStoreProvider
{
private static readonly IDictionary<string, IDocumentStore> _documentStores = new Dictionary<string, IDocumentStore>();
private static readonly DocumentStoreProvider _instance = new DocumentStoreProvider();
private DocumentStoreProvider()
{
var connectionStrings = ConfigurationManager.ConnectionStrings;
foreach (ConnectionStringSettings connectionString in connectionStrings)
{
var name = connectionString.Name;
var connection = connectionString.ConnectionString;
IDocumentStore currentStore = new DocumentStore { ConnectionStringName = name };
currentStore.Initialize();
currentStore.DatabaseCommands.EnsureDatabaseExists(name);
IndexCreation.CreateIndexes(Assembly.Load("Your.Assembly.Containing.Indexes"), currentStore);
_documentStores.Add(name, currentStore);
}
}
public static DocumentStoreProvider Instance
{
get { return _instance; }
}
public IDocumentStore GetDocumentStore(string key)
{
return _documentStores[key];
}
}
The usage can be following:
using (var session = DocumentStoreProvider.Instance.GetDocumentStore("Backup").OpenSession())
{
/* do stuff for chosen database... */
session.Store(something);
session.SaveChanges();
}

System.Data.EntityClient not recognized, by code.but recognized by web.config

When I simply run the project, data is get from server no problems, but there's a requirement of connection string to be in code.
According to material on net I did the following, but just cannot solve the error.
Error
The specified store provider cannot be found in the configuration, or is not valid.
domainservice
public class DomainService1 : LinqToEntitiesDomainService<EMPLOYEEEntities>
{
public override void Initialize(DomainServiceContext context)
{
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Provider = "System.Data.EntityClient";
builder.ProviderConnectionString = #"Data Source=A-63A9D4D7E7834\THIRD;Initial Catalog=EMPLOYEE;Integrated Security=True;";
builder.Metadata = string.Format(#"res://*/{0}.csdl|
res://*/{0}.ssdl|
res://*/{0}.msl", "Model1");
this.ObjectContext.Connection.ConnectionString = builder.ConnectionString;
base.Initialize(context);
}
web.config
<connectionStrings>
<add name="EMPLOYEEEntities"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=A-63A9D4D7E7834\THIRD;Initial Catalog=EMPLOYEE;Integrated Security=True;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
</connectionStrings>
The "System.Data.EntityClient" is a combination of many namespaces/libs therefore it is not recognized.
the right way would be,
public IQueryable<Table1> GetTable1()
{
// Specify the provider name, server and database.
string providerName = "System.Data.SqlClient";
string serverName = #"A-63A9D4D7E7834\THIRD";
string databaseName = "EMPLOYEE";
// Initialize the connection string builder for the
// underlying provider.
SqlConnectionStringBuilder sqlBuilder =
new SqlConnectionStringBuilder();
// Set the properties for the data source.
sqlBuilder.DataSource = serverName;
sqlBuilder.InitialCatalog = databaseName;
sqlBuilder.IntegratedSecurity = true;
sqlBuilder.MultipleActiveResultSets=True;
// Build the SqlConnection connection string.
string providerString = sqlBuilder.ToString();
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = providerName;
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = providerString;
// <add name="EMPLOYEEEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="Data Source=A-63A9D4D7E7834\THIRD;Initial Catalog=EMPLOYEE;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/Models.Model1.csdl|
res://*/Models.Model1.ssdl|
res://*/Models.Model1.msl";
Console.WriteLine(entityBuilder.ToString());
// EntityConnection conn = new EntityConnection(entityBuilder.ToString());
/*
using (EntityConnection conn =
new EntityConnection(entityBuilder.ToString()))
{
conn.Open();
Response.Write("this is a web application");
Console.WriteLine("Just testing the connection.");
conn.Close();
}*/
this.ObjectContext.Connection.ConnectionString = entityBuilder.ToString();
// this.ObjectContext.Connection.Open();
// this.ObjectContext.Connection.BeginTransaction();
// this.ObjectContext.Table1.OrderBy(q => q.ID);
IQueryable<Table1> results = this.ObjectContext.Table1.OrderBy(q => q.ID);
// this.ObjectContext.Connection.Close();
return results;
}