Wednesday, February 22, 2023

Connect SQL using X++ Code with ODBC

 Connect SQL using X++ Code with ODBC.


Control panel -> Administration -> 


	LoginProperty 	loginProperty;
	OdbcConnection 	odbcConnection;
	Statement 		statement;
	ResultSet 		resultSet;
	str 			sql, criteria;
	SqlStatementExecutePermission perm;

	str                             strConnectionString;
	str                             dbServer    = 'Server name';
	str                             dsnUser     = 'User name';
	str                             dsnUSerPwd  = 'Password';

	strConnectionString = strfmt("UID=%1;PWD=%2",dsnUser,dsnUSerPwd);
	strConnectionString = strfmt("DSN=%1;UID=%2;PWD=%3",'TestIntegration', dsnUser,dsnUSerPwd);

	// Set the information on the ODBC.
	loginProperty = new LoginProperty();
	// loginProperty.setDSN("TestIntegration");
	loginProperty.setServer(dbServer);
	loginProperty.setDatabase("TIntegration");
	loginProperty.setOther(strConnectionString);

	//Create a connection to external database.
	odbcConnection = new OdbcConnection(loginProperty);

	if (odbcConnection)
	{
		// Insert data 
		sql ="INSERT INTO [TestTable](FIELD1,FIELD2) VALUES";
		
		sql = sql + "('"+'1234511'+"','"+'Test1231'"')";

		perm = new SqlStatementExecutePermission(sql);
		perm.assert();
		statement = odbcConnection.createStatement();
		statement.executeUpdate(sql);
		statement.close();
			
		/*
		// getting data
		sql = "SELECT top 1 FIELD1 FROM TestTable where field2 = ";
		+ criteria
		+ " ORDER BY FIELD1, FIELD2 ASC ;";
		

		//Assert permission for executing the sql string.
		perm = new SqlStatementExecutePermission(sql);
		perm.assert();

		//Prepare the sql statement.
		statement = odbcConnection.createStatement();
		resultSet = statement.executeQuery(sql);


		while (resultSet.next())
		{
			Info(strFmt('%1', resultSet.getString(1)));
			Info(strFmt('%1', resultSet.getString(3)));
		}

		//Close the connection.
		resultSet.close();
		statement.close();*/
	}
	else
	{
		error("Failed to log on to the database through ODBC.");
	}


Keep Daxing!!

No comments:

Post a Comment