{"id":14070845,"url":"https://github.com/Beakerboy/VBA-SQL-Library","last_synced_at":"2025-07-30T08:33:04.398Z","repository":{"id":33646596,"uuid":"153445610","full_name":"Beakerboy/VBA-SQL-Library","owner":"Beakerboy","description":"Object-based Database Interaction for VBA. Create SQL Statements with VBA objects instead of string concatination.","archived":false,"fork":false,"pushed_at":"2024-07-30T01:36:07.000Z","size":778,"stargazers_count":67,"open_issues_count":11,"forks_count":16,"subscribers_count":4,"default_branch":"master","last_synced_at":"2024-08-13T07:18:20.893Z","etag":null,"topics":["library","sql","vba-excel"],"latest_commit_sha":null,"homepage":"","language":"VBA","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Beakerboy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-10-17T11:29:50.000Z","updated_at":"2024-08-06T21:41:48.000Z","dependencies_parsed_at":"2022-07-15T20:00:33.822Z","dependency_job_id":"fc1822bc-11be-445c-8623-fcc1ba84b535","html_url":"https://github.com/Beakerboy/VBA-SQL-Library","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Beakerboy%2FVBA-SQL-Library","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Beakerboy%2FVBA-SQL-Library/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Beakerboy%2FVBA-SQL-Library/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Beakerboy%2FVBA-SQL-Library/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Beakerboy","download_url":"https://codeload.github.com/Beakerboy/VBA-SQL-Library/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228110911,"owners_count":17871258,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["library","sql","vba-excel"],"created_at":"2024-08-13T07:08:07.692Z","updated_at":"2024-12-04T12:32:34.541Z","avatar_url":"https://github.com/Beakerboy.png","language":"VBA","readme":"[![Lint VBA](https://github.com/Beakerboy/VBA-SQL-Library/actions/workflows/lint_vba.yml/badge.svg?branch=master)](https://github.com/Beakerboy/VBA-SQL-Library/actions/workflows/lint_vba.yml)\n\u003ca href=\"https://beakerboy.github.io/VBA-SQL-Library/\"\u003e\u003cimg src=\"https://img.shields.io/badge/code-documented-green.svg\"/\u003e\u003c/a\u003e\n\nVBA SQL Library\n=====================\n\n### Object-Based Database Interaction for VBA\n\nEasily create SQL queries and execute them on a database. For an example on how to use this library with data objects, see the [VBA-Drupal-Library](https://github.com/Beakerboy/VBA-Drupal-Library). For other examples on using the library, refer to the unit tests.\n\nFeatures\n--------\n * [Database](#database)\n * [Login Form](#login-form)\n * [Static Queries](#static-queries)\n * [Insert](#insert)\n * [Select](#select)\n * [Update](#update)\n * [Delete](#delete)\n * [Helper Functions](#helper-functions)\n * [Unit Tests](#unit-tests)\n * [Documentation](#documentation)\n \n Setup\n-----\n\nOpen Microsoft Visual Basic For Applications and import each cls and bas and frm file into a new project. Name the project SQLlib and save it as an xlam file. Enable the addin. Within Microsoft Visual Basic For Applications, select Tools\u003eReferences and ensure that  \"Microsoft ActiveX Data Objects x.x Library\", \"Microsoft Scripting Runtime\", and SQLlib is selected.\n \n Security\n-----\nThis Library allows developers to create static or dynamic SQL statements using VBA objects. If the table names and field names are all known by the developer, and only field values, and conditional values will be supplied by the user, an SQLStaticQuery might be the best option. All user-supplied information will be sanitized before being added to the query. It also provides a login box to discourage hard-coding database authentication details. The dynamic query generating objects are best for cases where table names and field names are part of larger data objects, and the queries themselves are created by a larger system. This larger system should provide data sanitizing options to ensure malicious data does make it into a query. the [VBA-Drupal-Library](https://github.com/Beakerboy/VBA-Drupal-Library) is an example of such a system.\n\n Testing\n -----\nThe unit tests demonstrate many ways to use each of the classes. To run the tests, Import all the modules from the testing directory into a spreadsheet, install the [VBA-Unit-Testing library](https://github.com/Beakerboy/VBA-Unit-Tester) and type '=RunTests()' in cell A1. Ensure the Setup steps have all been successfully completed.\n \n Usage\n-----\n\n### Database\nCreate a new database connection:\n```vb\nDim MyDatabase As SQLDatabase\nSet MyDatabase = Create_SQLDatabase\nMyDatabase.DBType = \"mssql\"\nMyDatabase.DSN = \"foodb\"\n```\nSeveral different types of database execution can occur:\n * Execute(SQL) - Execute a statement (Insert or Update)\n * InsertGetNewID(SQLInsert) - Insert a record, and return the new primary key\n * Execute(SQLSelect, column) - Execute a statement and return a single value\n * Execute(SQLSelect) Execute a statement and return an array of values\n\n### Login Form\nThis form can be displayed to ask for the database credentials. This avoids having to hard-code username and passwords in the scrips.\n```vb\n'Open UserForm\nLogin.Show\n\n'After Button is pressed assign values\nMyDatabase.UserName = Login.Username\nMyDatabase.Password = Login.Password\nUnload Login\n```\n### Static Queries\nDevelopers can create static queries, while ensuring that user inputed data will interact with the database successfully.\nItems in bold are required\n * .Query = __query__\n * .AddArgument __placeholder__, __value__\n * .ClearArguments\n \n#### Example 1\n```vb\nDim MyStaic as SQLStaticQuery\nSet MyStatic = Create_SQLStaticQuery\nMyStatic.Query = \"SELECT name FROM users WHERE id=:id\"\nMYStatic.addArgument \":id\", 4\n```\nWill produce the SQL\n```sql\nSELECT name FROM users WHERE id=4;\n```\nThe SQL statement can be easily reused with different user-supplied values for the ID without the need to recreate the object.\n\n### Insert\nThe SQLInsert Object has many options. Items in bold are required.\n * .Table     = __table__\n * .Fields    = Array(__field1__, _field2_, ...)\n * .Values    = Array(__value1__, _value2_, ...)\n * .From      = __SQLSelect__\n * .Returning = __field__\n\nThe Insert object can create both INSERT VALUES and INSERT SELECT statements. Multiple inserts can be performed in one statement if the values array is 2 Dimensional.\n\n#### Example 1 - Insert Values\nTo produce this SQL Stament:\n```sql\nINSERT INTO users (username, first_name, password) VALUES ('admin', 'Alice', 'secret');\n```\n\nUse the Following in VBA-SQL-Library\n```vb\n'Initialize the object and assign a table name\nSet MyInsert = Create_SQLInsert\nMyInsert.table = \"users\"\n\n'Set The Fields\nMyInsert.Fields = Array(\"username\", \"first_name\", \"password\")\n\n'Set the Values\nMyInsert.Values = Array(str(\"admin\"), str(\"Alice\"), str(\"secret\"))\n\n'Execute the query\nMyDatabase.Execute MyInsert \n```\n\n#### Example 2 - Insert Select\nTo produce this SQL Stament:\n```sql\nINSERT INTO bank_account (account_number, open_date, user_id)\n    SELECT (10, 570000051, user_id) FROM users WHERE username = 'admin';\n````\nUse the Following in VBA-SQL-Library\n```vb\n'Create the SELECT Statement\nSet SQL = Ceate_SQLSelect\n\n'We don't escape the \"user_id\" because it is a field name, not a string\nSql.Fields = Array(10, 5770000051, \"user_id\")\nSql.Table = \"users\"\nSql.addWhere \"username\", str(\"admin\")\n\n'Initialize the object and assign a table name\nSet MyInsert = Create_SQLInsert\nWith MyInsert\n    .table = \"bank_account\"\n    .Fields = Array(\"account_number\", \"open_date\", \"user_id\")\n    Set .From = Sql\nEnd With\n\n'Execute the query, returning the newly created primary Key\nID = MyDatabase.InsertGetNewID(MyInsert)\n```\n\n#### Example 3 - Insert Multiple Values\n\nTo produce this SQL Stament:\n```sql\nINSERT INTO users (username, first_name, password) VALUES ('admin', 'Alice', 'secret'), ('editor', 'Bob', 'super-secret');\n```\n\nUse the Following in VBA-SQL-Library\n```vb\n'Initialize the object and assign a table name\nSet MyInsert = Create_SQLInsert\nMyInsert.table = \"users\"\n\n'Set The Fields\nMyInsert.Fields = Array(\"username\", \"first_name\", \"password\")\n\n'Set the Values\nDim Values2D(1) As Variant\nValues2D(0) = Array(\"'admin'\", \"'Alice'\", \"'secret'\")\nValues2D(1) = Array(\"'editor'\",\"'Bob'\", \"'super-secret'\")\nMyInsert.Values = Values2D\n\n'Execute the query\nMyDatabase.Execute MyInsert \n```\n\n### Select\nThe Select Object has many options. Items in bold are required\n * .Table = __table__\n * .addTable __table__, _alias_\n * .Fields = Array(__field1__, _field2_, ...)\n * .AddField __field__, _alias_\n * .AddExpression __expression__, _alias_    \n * .Distinct\n * .InnerJoin __table__, _alias_, _condition_\n * .LeftJoin __table__, _alias_, _condition_\n * .RightJoin __table__, _alias_, _condition_\n * .AddJoin __joinType__, __table__, _alias_, _condition_\n * .OrderBy __field__, _direction_\n * .AddWhere __field__, __value__, _operation_, _groupType_\n * .GroupBy __field_\n * .AddHaving __field__, __value__, _operation_, _groupType_\n * .Union __query__, _type_\n\n#### Example 1\nWe can execute a select statement and receive the results as a single value, or an array of values:\n```sql\nSELECT id FROM users WHERE username='admin';\n```\n\n```vb\nSet MySelect = Create_SQLSelect\nWith MySelect\n    .Fields = Array(\"id\")\n    .Table = \"users\"\n\n    'Need to escape the string\n    .AddWhere \"username\", str(\"admin\")\nEnd With\n\nID = MyDatabase.Execute(MySelect, \"id\")\n```\nWHERE clauses can be added and grouped together. The following changes the query to:\n```sql\nSELECT id FROM users WHERE username='admin' AND id\u003c10;\n```\n```vb\nMySelect.AddWhere \"id\", 10, \"\u003c\", \"AND\"\n```\nA SQLWhereGroup can abe be added using SQLSELECT.AddWhereGroup. This is necessary for a where clause like:\n```sql\nSELECT id FROM users WHERE (a=1 AND b=2) OR (c = 3 AND d = 4)\n```\nThe SQLSelect Object can create Queries with \"GROUP BY ... HAVING ...\" sections.\n```sql\n... GROUP BY user_type HAVING age\u003e1;\n```\n```vb\nMySelect.GroupBy = Array(\"user_type\")\nMySelect.AddHaving = \"age\", \"1\", \"\u003e\"\n```\nA query can be run as DISTINCT by flagging the Distinct property\n```vb\nMySelect.Distinct\n```\n#### Example 2\nWe can add table aliases and joins as well\n```sql\nSELECT u.id, c.hex FROM users u INNER JOIN colors c ON u.favorite=c.name ORDER BY u.id DESC\n```\n```vb\nSet MySelect = Create_SQLSelect\nWith MySelect\n    .Fields = Array(\"u.id\", \"c.hex\")\n    .addTable \"users\", \"u\"\n    .innerJoin \"colors\", \"c\", \"u.favorite=c.name\"\n    .OrderBy \"u.id\", \"DESC\"\nEnd With\n```\n\n#### Example 3\nWe can include multiple tables without a join if you need to.\n```sql\nSELECT u.id, c.hex FROM users u, colors c WHERE u.favorite=c.name ORDER BY u.id DESC\n```\n```vb\nSet MySelect = Create_SQLSelect\nWith MySelect\n    .Fields = Array(\"u.id\", \"c.hex\")\n    .addTable \"users\", \"u\"\n    .addTable \"colors\", \"c\"\n    .AddWhere \"u.favorite\" \"c.name\"\n    .OrderBy \"u.id\", \"DESC\"\nEnd With\n```\n\n### Update\n#### Example 1 \nTo produce this SQL Statement:\n```sql\nUPDATE users SET username='old_admin' WHERE username='admin'\n```\n```vb\nSet MyUpdate = Create_SQLUpdate\nWith MyUpdate\n    .Fields = Array(\"username\")\n    .Values = Array(\"old_admin\")\n    .Table = \"users\"\n\n    'Need to escape the string\n    .AddWhere \"username\", str(\"admin\") \nEnd With\n\nMyDatabase.Execute MyUpdate\n```\n\n### Delete\n#### Example 1 \nTo produce this SQL Statement:\n```sql\nDELETE FROM users WHERE username='admin'\n```\n```vb\nSet MyDelete = Create_SQLDelete\nWith MyUpdate\n    .Table = \"users\"\n    'Need to escape the string\n    .AddWhere \"username\", str(\"admin\") \nEnd With\n\nMyDatabase.Execute MyDelete\n```\n\n### HelperFunctions\nThe library includes a handful of helper functions. \n* Date/Time manipulation, toIso() and toUnix().\n* String encapsulation str() to add single quotes around strings and escape contained single-quotes\n\n### Unit Tests\nIf you would like to run the unit tests, import all the library files including the files in \"testing\" into an Excel workbook. In some cell, type \"=RunUnitTests()\". Any failures will open a messagebox stating the expected output and what was actually received by the library.\n\n### Documentation\nAll classes are [documented](https://beakerboy.github.io/VBA-SQL-Library/) using Naturaldocs syntax.\n","funding_links":[],"categories":["VBA"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBeakerboy%2FVBA-SQL-Library","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FBeakerboy%2FVBA-SQL-Library","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FBeakerboy%2FVBA-SQL-Library/lists"}