I would like to write to SQL database by Java based Azure Functions.
I have SQLconnstring of JDBC in local.settings.json. How to get this connection correctly from settings file instead of hard coding to java file?
package com.function;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Azure Functions with Azure Storage Queue trigger.
*/
public class TopicTriggerSQLOutput {
/**
* This function will be invoked when a new message is received at the specified path. The
message contents are provided as input to this function.
*/
#FunctionName("TopicTriggerSQLOutput")
public void run(
#ServiceBusTopicTrigger(
name = "message",
topicName = "newtopic",
subscriptionName = "newsubscription",
connection = "topicconnstring"
) String message,
final ExecutionContext context
) {
/*Creating SQL Connection. I need help here:
*/
/*How to get connection string from local.settings.json instead of hard coding?*/
String connectionUrl =
"jdbc:sqlserver://yourserver.database.windows.net:1433;"
+ "database=AdventureWorks;"
+ "user=yourusername#yourserver;"
+ "password=yourpassword;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "loginTimeout=30;";
try (Connection connection = DriverManager.getConnection(connectionUrl);) {
// SQL Code here.
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
//context.getLogger().info(message);
}
}
You can use System.getenv("") to get the value from local.settings.json file. For example, we can use String connectionUrl =System.getenv("SQLConnectionString"); to get the sql connection string in the local.settings.json file.
Related
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
am getting an exception as java.sql.Connection.prepareStatement(String) because con is null, I don't know why as I have already added MySQL Connector jar file.
import java.sql.Connection;
import java.sql.PreparedStatement;
public class Studentdao {
public static boolean insertStudenttoDB(Student st) {
boolean f=false;
try {
Connection con =CP.createc();
//jdbc code
String q="insert into students(sname,sphone scity)values(?,?,?)";
PreparedStatement pstmt=con.prepareStatement(q);
pstmt.setString(1,st.getStudentname());
pstmt.setString(2,st.getStudentcity());
pstmt.setLong(3,st.getStudentphone());
//execute
pstmt.executeUpdate();
f=true;
}
catch(Exception e) {
e.printStackTrace();
}
return f;
}
}
This is my connection program
import java.sql.Connection;
import java.sql.DriverManager;
public class CP {
static Connection con;
//load driver
public static Connection createc() {
try {
Class.forName("com.sql.jdbc.Driver");
//creating connection
String user="mysql";
String password="mysql";
String url="jdbc:mysql://localhost:3306/student_manage";
con=DriverManager.getConnection(url,user,password);
}catch(Exception e) {
e.printStackTrace();
}
return con;
}
}
Incorrect class name
You appear to have an incorrect class name, if you are using the Connector/J product as your JDBC driver.
Section 3.6.1 of the Connector/J manual shows the use of "com.mysql.cj.jdbc.Driver" versus your use of "com.sql.jdbc.Driver". Here is their code example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.cj.jdbc.*
// or you will have problems!
public class LoadDriver {
public static void main(String[] args) {
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
}
}
DataSource
Note that your use of Class.forName is generally not needed in modern Java. The JDBC architecture was years ago revamped so that now drivers are automatically located and loaded using the Java Service Provider Interface (SPI) technology.
I do suggest you make a habit of using a DataSource to obtain connections rather than calling on the DriverManager. Using DataSource makes your code much more flexible. You will be able to switch JDBC drivers, add connection pooling, and externalize configuration info (server address, database name, user name, password, etc.) for deployment.
Usually your JDBC driver comes with a basic implementation of DataSource. Check the documentation for all the various options you can set, specific to your database (MySQL in this case).
For MySQL, I understand the implementation of DataSource currently provided in Connector/J is com.mysql.cj.jdbc.MysqlDataSource. Caveat: I make regular use of Postgres & H2, not MySQL, so I may not be up-to-date.
See my Answer to another Question for source code of a full example of connecting and working with MySQL. Here are the parts relating to DataSource and Connection.
private DataSource configureDataSource ( )
{
System.out.println( "INFO - `configureDataSource` method. " + Instant.now() );
com.mysql.cj.jdbc.MysqlDataSource dataSource = Objects.requireNonNull( new com.mysql.cj.jdbc.MysqlDataSource() ); // Implementation of `DataSource` bundled with H2.
dataSource.setServerName( "db-mysql-sfo3-422-do-user-8982-1.x.db.ondigitalocean.com" );
dataSource.setPortNumber( 24_090 );
dataSource.setDatabaseName( "defaultdb" );
dataSource.setUser( "scott" );
dataSource.setPassword( "tiger" );
return dataSource;
}
Early in the lifecycle of your app, instantiate and retain the DataSource object returned from that method. Remember, a DataSource holds only the configuration details; it is not an open resource itself, and need not be closed.
DataSource dataSource = this.configureDataSource();
To open a connection, pass the DataSource to your method that wants to connect to the database.
private void dumpTable ( DataSource dataSource ) { … }
Here is a piece of that dumpTable method.
Notice the use of try-with-resources syntax to automatically close the open resources in the order in which they were declared, even in case of failure with exceptions being thrown.
String sql = "SELECT * FROM event_ ;";
try (
Connection conn = dataSource.getConnection() ; // 🡄 Use the passed `DataSource` object to ask for a `Connection` object.
Statement stmt = conn.createStatement() ;
ResultSet rs = stmt.executeQuery( sql ) ;
)
{
…
}
catch ( SQLException e )
{
e.printStackTrace();
}
here's the code I tried to connect java class with mysql. Make sure you have to add the required driver to your libraries.
import java.sql.Connection;
import java.sql.DriverManager;
public class Server {
public static Connection getConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
String urls = "127.0.0.1";//you can even replace this with localhost
String username = "yourusername";
String password = "1234";
Connection conn = DriverManager.getConnection("jdbc:mysql://"+urls+":3306/yourdb?useUnicode=yes&characterEncoding=UTF-8", username, password);
return conn;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
I was trying to create a dynamic JDBC connection in java to connect to snowflake.
I am stuck at a point ,how can i pass the parameter from my property file into snowflake connection file
Please find the attached code
package com.cisco.export.utils;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import com.cisco.config.Configuration;
public class SFDbConnection {
public Connection getConnection(Configuration config) throws SQLException{
Connection connection=null;
try {
System.out.println(config.getProp("sf.driverclass"));
System.out.println(config.getProp("sf.url"));
System.out.println(config.getProp("sf.account"));
System.out.println(config.getProp("sf.username"));
System.out.println(config.getProp("sf.password"));
System.out.println(config.getProp("sf.warehouse"));
System.out.println(config.getProp("sf.db"));
System.out.println(config.getProp("sf.schema"));
System.out.println(config.getProp("sf.role"));
Class.forName(config.getProp("sf.driverclass"));
String connectStr = "jdbc:snowflake://mysnowflakeaccount.us-east-1.snowflakecomputing.com";
connection = DriverManager.getConnection()
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
Can some one Help me how can i make the parameters inside the getConnection() dynamic.
Appreciate your help.
Thanks,
Nikhil
The Snowflake JDBC Driver accepts connection properties via the connection-string or via a java.util.Properties class object.
Using the properties in a connection string:
String sfAccount = config.getProp("sf.account");
String sfUsername = config.getProp("sf.username");
String sfPassword = config.getProp("sf.password");
String sfWarehouse = config.getProp("sf.warehouse");
String sfDatabase = config.getProp("sf.db");
String sfSchema = config.getProp("sf.schema");
String sfRole = config.getProp("sf.role");
String connectionString =
String.format("jdbc:snowflake://%s.snowflakecomputing.com/?role=%s&warehouse=%s&db=%s&schema=%s",
sfAccount,
sfRole,
sfWarehouse,
sfDatabase,
sfSchema
);
return DriverManager.getConnection(connectionString, sfUsername, sfPassword);
The com.cisco.config.Configuration class is not a known public API type, but if it can be translated to a java.util.Properties object, you can pass it when building a connection. Here's a direct conversion:
java.util.Properties props = new java.util.Properties();
String connectionString =
String.format(
"jdbc:snowflake://%s.snowflakecomputing.com",
config.getProp("sf.account")
);
props.setProperty("user", config.getProp("sf.username"));
props.setProperty("password", config.getProp("sf.password"));
props.setProperty("role", config.getProp("sf.role"));
props.setProperty("warehouse", config.getProp("sf.warehouse"));
props.setProperty("db", config.getProp("sf.db"));
props.setProperty("schema", config.getProp("sf.schema"));
return DriverManager.getConnection(connectionString, props);
I have java based Azure Functions with, which is writing to Azure SQL.
However I get error when Function is triggered.
What I need to do with VS Code for driver issue?
I'm fine with JDBC or any other drive which is best with Azure Functions
https://learn.microsoft.com/en-us/sql/connect/jdbc/step-3-proof-of-concept-connecting-to-sql-using-java?view=sql-server-ver15
ERROR:
17.4.2020 13.06.39] java.sql.SQLException: No suitable driver found for jdbc:sqlserver://sql...;
[17.4.2020 13.06.39] Function "TopicTriggerSQLOutput" (Id: 70a1ce4c-3828-4280-81cf-dafa61956cb5)
invoked by Java Worker
[17.4.2020 13.06.39] at java.sql.DriverManager.getConnection(DriverManager.java:689)
CODE:
package com.function;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
/**
* Azure Functions with Azure Storage Queue trigger.
*/
public class TopicTriggerSQLOutput {
/**
* This function will be invoked when a new message is received at the specified path. The
message contents are provided as input to this function.
*/
#FunctionName("TopicTriggerSQLOutput")
public void run(
#ServiceBusTopicTrigger(
name = "message",
topicName = "newtopic",
subscriptionName = "newsubscription",
connection = "topicconnstring"
) String message,
final ExecutionContext context
) {
/*Creating SQL Connection. I need help here:
https://learn.microsoft.com/en-us/sql/connect/jdbc/step-3-proof-of-concept-connecting-to-sql-
using-java?view=sql-server-ver15
*/
String connectionUrl = "jdbc:sqlserver://sql...";
ResultSet resultSet = null;
try (Connection connection = DriverManager.getConnection(connectionUrl);
Statement statement = connection.createStatement();) {
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT TOP 10 artist FROM [dbo].[RadioEventsTarget]";
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
System.out.println(resultSet.getString(2) + " " + resultSet.getString(3));
}
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
//context.getLogger().info(message);
}
}
What I need to do with VS Code for driver issue?
You need to add the jdbc driver dependency to the pom.xml file. Here is the dependency sample I used to connect to Azure SQL.
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.2.2.jre8</version>
</dependency>
Reference:
https://learn.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-ver15
I'm new with Java Azure Functions.
I get Service Bus Trigger and Azure SQL output working, but need now advice with parsing json message.
I have Service Bus trigger, which provides data like "{ "name": "John","city": "NYC"}"
I would like to store this to Azure SQL. How to parse JSON and store to SQL?
package com.function;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
//import java.sql.ResultSet;
/**
* Azure Functions with Azure Storage Queue trigger.
*/
public class TopicTriggerSQLOutput {
/**
* This function will be invoked when a new message is received at the specified path. The
message contents are provided as input to this function.
*/
#FunctionName("TopicTriggerSQLOutput")
public void run(
#ServiceBusTopicTrigger(
name = "message",
topicName = "newtopic",
subscriptionName = "newsubscription",
connection = "topicconnstring"
) String message,
final ExecutionContext context
) {
String connectionUrl = "jdbc:sqlserver:...database.windows.net;loginTimeout=30;";
try (Connection connection = DriverManager.getConnection(connectionUrl);
Statement statement = connection.createStatement();) {
context.getLogger().info("SeviceBus message" + message); // I get JSON returned
correctly here.
// How to parse message json string?
// Create and execute a SELECT SQL statement.
String InsertSql = "INSERT INTO [dbo].[Target_Table] ([NAME],[CITY]) VALUES
('NameString', 'CityString')";
// insert the data
statement.executeUpdate(InsertSql);
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
context.getLogger().info("Message: " + message);
}
}
Problem solved with importing Gson. https://www.tutorialspoint.com/gson/gson_first_application.htm
import com.google.gson.Gson;
Student myjson = gson.fromJson(jsonString, myjson.class);
I am trying to connect to a cube i created in SSMS,using JDBC (My database name is AdventureWorks).
Where should i put connection URL, and
Is my connection URL correct or not?
I have already added the jar files for olap4j, but on executing i am getting classNotFoundException. This is the code I have used:
package oLapConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.olap4j.OlapConnection;
public class Olap {
public static void main(String [] args) throws SQLException {
// Load the driver
try {
Class.forName("org.olap4j.driver.xmla.XmlaOlap4jDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Connect
final Connection connection =
DriverManager.getConnection(
// This is the SQL Server service end point.
"jdbc:xmla:Server=http://localhost/olap/msmdpump.dll;Catalog=myCatalog"
// Tells the XMLA driver to use a SOAP request cache layer.
// We will use an in-memory static cache.
+ ";Cache=org.olap4j.driver.xmla.cache.XmlaOlap4jNamedMemoryCache"
// Sets the cache name to use. This allows cross-connection
// cache sharing. Don't give the driver a cache name and it
// disables sharing.
+ ";Cache.Name=MyNiftyConnection"
// Some cache performance tweaks.
// Look at the javadoc for details.
+ ";Cache.Mode=LFU;Cache.Timeout=600;Cache.Size=100",
// XMLA is over HTTP, so BASIC authentication is used.
null,
null);
// We are dealing with an olap connection. we must unwrap it.
final OlapConnection olapConnection = connection.unwrap(OlapConnection.class);
// Check if it's all groovy
ResultSet databases = olapConnection.getMetaData().getDatabases();
databases.first();
System.out.println(
olapConnection.getMetaData().getDriverName()
+ " -> "
+ databases.getString(1));
// Done
connection.close();
}
}
Thanks for you help. You can tell me any related articles or links that would help. Please guide me if the question is not clear.