Как создавать базы данных и как с ними работать. Я это делаю, потому что все последующие статьи будут работать с базами только через ADO (пока это будет Access, а через пару месяцев я расскажу про MS SQL Server).
Запусти Access и выбери в меню Файл->Создать. В мастере создания базы выбери пункт "База данных" и нажми "ОК". Тебе предложат выбрать имя базы и место расположения, укажи что угодно, а я оставил значение по умолчанию db1.mdb .
После этого Access создаст базу и сохранит её по указанному пути. А ты увидишь окно, в котором и происходит работа с базой. Слевой стороны окна находится колонка выбора объектов, с которымы ты хочешь работать. Первым находится пункт "Таблицы" (он выделен по умолчанию) который и будет нас интересовать. Если этот объект у тебя не выделен, то выдели его. В окне справа находится три пункта:
Создание таблицы в режиме конструктора
Создание таблицы с помощью мастера
Создание таблицы путём ввода данных
С помощью этих команд можно создать таблицы внутри нашей, т.е. твоей базы данных. Ты уже должен знать, что в отличии от таблиц Paradox и Foxpro (которые состоят из одной таблицы), базы данных могут хранить в одном файле несколько таблиц.
В это же окно будет добавляться список созданных тобой таблиц. Щёлкни по "Создание таблицы в режиме конструктора" чтобы создать новую таблицу в базе данных.
Сверху находится сетка в которой ты вводишь поля таблицы, их тип и описание (последнее не обязательно). Когда ты вписал в сетку имя нового поля и указал тип, внизу окна появляются свойства нового поля. В зависимости от типа поля изменяется и количество свойств. Вот самые основные:
Максимальная длина поля. Для текстового поля размер не может быть больше 255. Если текст длиннее, то надо использовать "Поле Memo".
Формат поля. Здесь ты можешь указать внешний вид данных. Например, поле может выглядеть как "Yes/No" для логических полей, или например "mm yyyy" для поля даты.
Маска ввода. Здесь мы вводим маску, которая отвечает за отображение поля при редактировании. Если ты щёлкнешь на кнопке с точками "..." в строке "Маска ввода", то увидишь мастер,.
Значение по умолчанию. Умолчание, оно и в африке по умолчанию.
Обязательное поле. Если пользователь не введёт сюда значение, то появится сообщение об ошибке. Такое поле не может быть пустым.
Пустые строки. Похоже на предыдущий, потому что это поле тоже не может быть пустым.
Индексированное поле. Может быть неиндексированным, индексированным с допуском совпадений, и индексированным без допуска совпадений. Основной индекс всегда без допуска совпадений. Остальные желательно с допуском.
Сжатие Юникод - позволяет сжать данные в соответствии с Юникод.
Создай шесть полей:
Key1 - числовой. Это у нас будет ключик. Размер поля - "Длинное целое". Индексированное поле - "Да (Совпадения не допускаются)".
Фамилия - текстовый. Размер поля - 50. Индексированное поле - "Да (Допускаются совпадения)".
Имя - текстовый. Размер поля - 50. Индексированное поле - "Да (Допускаются совпадения)".
Телефон - текстовый. Размер поля - 10. Индексированное поле - "Да (Допускаются совпадения)".
e-mail - текстовый. Размер поля - 20. Индексированное поле - "Да (Допускаются совпадения)".
Город - числовой. Размер поля - Длинное целое. Индексированное поле - "Нет".
Помимо этого, у всех полей значение "Обязательно поле" стоит в "Нет", и "Пустые строки" выставлено в "Да".
Теперь выдели первое поле (Key1), щёлкни правой кнопкой мыши и выбери пункт "Ключевое поле".
Создай ещё одну таблицу "Справочник городов" с полями Key1 (числовое, ключевое) и город (текстовое, длинна 50). Сохрани таблицу.
Для открытия для заполнения полей таблицы нужно щёлкнуть на кнопке "Открыть". Для редактирования уже созданной таблицы нужно щёлкнуть на кнопке "Конструктор".
Теперь переходим в Delphi. Создай новый проект. Выбери File->New и создай новый модуль типа "DataModule". Брось на форму DataModule2 компонент ADOConnection из закладки ADO.
Щёлкни дважды по ADOConnection1. Появится знакомое окно (если ты читал статью в октябрьском номере). Выдели CheckBox "Use Connection String" и нажми кнопку "Build". Появится окно выбора поставщика драыйвера для работы с базой данных. Выбери "Microsoft Jet 4.0 OLE DB Provider". Здесь 4.0 обозначает номер версии и необходим для работы с Access 2000. Если у тебя установлен Office 97, то тебе достаточно версии 3.51. Нажми кнопку "Далее" и выбери в появившемся окне имя базы данных. Нажимай "ОК" и ещё в одном окне "ОК".
Теперь измени у ADOConnection1 свойство LoginPrompt на false, чтобы при коннекте с базой у тебя не запрашивали пароль (всё равно мы его не задали). Теперь можно коннектится к базе, для этього измени свойство Connected на true.
Теперь брось на эту же форму DataSource с закладки "Data Access" и ADOTable с закладки ADO.
У ADOTable установи следующие свойства:
Connection - ADOConnection1
TableName - "Главная таблица"
Active - true
У DataSource1 установи свойство DataSet в ADOTable1. Перейди в форму 1 (Form1). Выбери File->Use Unit и в появившемся окне выбери Unit2, чтобы подключить к Form1 наш модуль DataModule2.
Поставь на форму DBGrid с закладки "Data Controls". Измени его свойства DataSource на "DataModule2.DataSource1". Запускай программу и используй.
Другие работы по теме:
Специфика создания баз данных и работы в Microsoft Access
Начало работы в Microsoft Access. Основные моменты создания несложной базы данных: создание титульного листа в режиме конструктор, базы данных, порядок занесения данных для базы в режиме презентации. Особенности оформления отчета и настройки программы.
Создание баз данных в Microsoft Access
Министерство просвещения Украины Национальная Горная Академия СОЗДАНИЕ ФАЙЛА И ТАБЛИЦ БАЗЫ ДАННЫХ МАСТЕРОМ И ПО ЗАДАННОЙ ЛОГИЧЕСКОЙ МОДЕЛИ Лабораторная работа Access 97
Проектирование и реализация базы данных
Расчет предельно-допустимых сбросов (ПДС) для предприятий различных видов деятельности. Разработка и реализация базы данных "ПДС". Схема данных и программные тексты.
Работа с базами данных
Microsoft Access как мощное приложение, предлагающее широкий диапазон средств для эффективного управления информацией, оценка его возможностей, содержание и назначение. Создание и заполнение таблицы базы данных о студентах в режиме конструктора.
Создание базы данных
Авторизация с каталогами проектирования базы данных магазина. Задачи базы данных: учет всех товаров, поиск и выдача данных о клиентах, адрес, телефоны, цена и наличие товара. Этапы проектирования базы данных. Схема данных, создание запросов и их формы.
Проектирование баз данных MS Access
Проектирование базы данных Access. Система управления базами данных. Создание и обслуживание базы данных, обеспечение доступа к данным и их обработка. Постановка задач и целей, основных функций, выполняемых базой данных. Основные виды баз данных.
База данных MS Access
Министерство общего и профессионального образования РФ Ростовский государственный экономический университет «РИНХ» Кафедра информационных технологий
Настройка параметров приложения
Санкт-Петербургский Государственный Политехнический университет Лабораторная работа №1 санкт-петербург 2009 год Настройка параметров приложения
Dsl Vs Cable Essay Research Paper 22
Dsl Vs. Cable Essay, Research Paper 2.2 Why focus on Internet access? Internet access has several desirable properties as an application to consider for exercising residential infrastructure. Internet technology is
Common Law Essay Research Paper Communications LawIn
Common Law Essay, Research Paper Communications Law In San Franciso, two of Alameda County’s six municipal courts have limited public access to criminal court records after a Legal Aid Society lawyer requested it; others are waiting an opinion from the county counsel about its constitutionality.
Marketing Plan Essay Research Paper We live
Marketing Plan Essay, Research Paper We live in a world where consumers are demanding access to information and service anywhere, anytime, and from any device. For most people, Cell phones will be the devices, which provide them with their first access to the Internet. Time is the most precious commodity and convenience is everything.
Privacy In The Information Age Essay Research
Paper Privacy in the Information Age: I N T R O D U C T I O N ———————————————————————— The world is changing rapidly. There used to be a time when we could be confident that no one could learn too much about our personal lives. There used to be a time when information was merely a way of keeping records. That time is gone and with it went a large amount of what we might call our personal privacy.
Information Methods Essay Research Paper The aim
Information Methods Essay, Research Paper The aim of this assignment was to show and explain the value and importance of information and the tools readily accessible to us as students. We were to investigate the individual components of Access, Excel, Word and Powerpoint, then to transform, manipulate and present the information we gathered.
The Growth Of The Internet Essay Research
Paper The Internet s growth and size have grown vastly over the last couple of years due to rapid interest in particular to businesses that want their customers to access their products online. The Internet s size alone has ballooned to an estimated 89.4 million people who actually surfed in August 2000, a 1.7 % increase from July.
What Really Is A Hacker Essay Research
Paper What Really is a Hacker? Dan Parks Julie Jackson – Instructor CIS 101 11-18-96 There is a common misconception among the general public about what constitutes a hacker and what hacking is. Hacking is defined as “gaining
Lone Man Essay Research Paper Thank you
Lone Man Essay, Research Paper Thank you for your interest in NetZero. As part of our commitment to maintain high quality, free Internet access for all of our users, we are currently limiting the number of new downloads of our software on a daily basis.
America Online Essay Research Paper America Online
America Online Essay, Research Paper America Online To Unveil Flat Fee For Internet Access The Internet is becoming more popular and more widely used, and the Market for internet access is growing rapidly. To stay
Health Care Ethics Essay Research Paper Improving
Health Care Ethics Essay, Research Paper Improving Access to Health Care for the Uninsured For decades, the American system of health care has relied primarily on employer-sponsored insurance programs as a gateway through which individual s access health care services. Gaps have been filled in through public insurance programs such as Medicare, Medicaid, the State Children s Health Insurance Program (SCHIP) and other more locally-based programs to cover elderly, disabled and certain low income populations who cannot access the employer-based market.
Database Design Essay Research Paper Before you
Database Design Essay, Research Paper Before you use Microsoft Access to actually build the tables, forms, and other objects that will make up your database, it is important to take time to design your database. A good database design is the keystone to creating a database that foes what you want it to do effectively, accurately, and efficiently.
Market Power In The Deregulation Of Electicity
Essay, Research Paper Market power, which is at the heart of the debate over ownership and control of the electricity transmission network, has been identified by the FERC (Federal Energy Regulatory Commission) as a potential impediment to the development of an unencumbered competitive market for electricity.
Wireless Application Protocol Essay Research Paper Wireless
Wireless Application Protocol Essay, Research Paper Wireless Application Protocol (WAP) Background Market study has shown that the number of mobile users is exceeding the number of PC users. Some of the industry leaders have created a forum to evolve an industry standard for providing internet access to users over wireless access.
Social Change Essay Research Paper In the
Social Change Essay, Research Paper In the article, “The Rhetorician as an Agent of Social Change”, written by Ellen Cushman, I believe that the way I feel about ACCESS is shown. “A gift that is not returned can become a debt, a lasting obligation. Depending on the terms of the exchange, this obligation can either be in the form of a monetary debt, which imposes “overtly economic obligations by the usurer”, or in the form of ethical debt, which produces “moral obligations and emotional attachment created and maintained by the generous gift.” (380)
Computer In Buisness Essay Research Paper The
Computer In Buisness Essay, Research Paper The personal computer has changed the way the world does business. Through the possibility of customers being able to access the Internet, They
Entering The PostModern Era Essay Research Paper
How does a people determine that a movement to a new era has occurred? Although there was no newspaper headline announcing the beginning of postmodernism, it is very evident that American culture took a turn in the 1960’s, and, as always, the arts began to reflect the changes in our culture.
Pbs Essay Research Paper PROCESS BASED SECURITY
Pbs Essay, Research Paper PROCESS BASED SECURITY, WHAT IS IT AND HOW IT WILL CHANGE YOUR COMPUTER?S LIFE This note is for the purpose of explaining a new way to implement operating system security called process-based security. First, an explanation of traditional operating system security is given. Next, an explanation of process-based security is given.
Gender And Information Technology Essay Research Paper
Gender and Information Technology Information and communications are playing an increasingly important role in economic and social development. Meanwhile, the recent developments in communications technology have progressively reduced the barriers to communicating over distances.
Digital Divide Essay Research Paper The Digital
Digital Divide Essay, Research Paper The Digital Divide a Social Issue ? When we talk about the digital divide its not as clear cut as people think, if 98% of the planets population have failed to be touched by the internet revolution then surly we need to look at more than one way to bridge the gap, the united nations, the group of eight, university departments and community groups across the world are clambering for a piece of the action an example being that in Britain Tony Blair has promised universal access by 2005 and is poring millions of pounds into disadvantaged communities.